0

无法确定如何将短语字符串与文件流中的短语匹配。我正在处理的文件包含随机单词,例如:

3 little pigs built houses and 1 little pig went to the market

等多行。模式字符串中可能有特殊字符,例如,V++ **A我需要LITERAL标志以便可以找到它们,而不是在正则表达式中具有特殊含义。

我的模式是pattern = Pattern.compile(searchString, Pattern.LITERAL);

使用“ little pig”作为我的模式字符串,matcher.find()我可以找到 2 个匹配项:“小猪”和“小猪”。但是,我只希望它匹配“小猪”。

我能做些什么?我考虑过使用matcher.lookingAt()ormatcher.matches()但当我不能依赖我匹配的文件字符串短语位于单独的行时,我不知道如何设置适当的区域。

4

4 回答 4

0

\\s|^编辑4(最后一个):一开始就完全忘记了需要

编辑 3:做了一些调整以考虑到 searchString 之后的 char 可能是字符串的结尾search P = Pattern.compile("\\s"+Pattern.quote(searchString)+"(\\s|$)");

编辑2:好的,我明白了!searchP = Pattern.compile("\\s"+Pattern.quote(searchString)+"\\s");

不知道为什么我没有注意到引用方法……哦,第一次做所有事情:)

编辑:事实证明我超前了 - 代码对特殊字符根本没有帮助,因为literalP在searchP中转换为String并且丢失LITERAL了用户String的规则。

我想我明白了!下面将用户的字符串转换为文字,然后将其放入允许\\s. 但是,如果有人发现它有问题,请告诉我。

Pattern literalP = Pattern.compile(searchString, Pattern.LITERAL);
Pattern searchP = Pattern.compile("\\s"+literalPattern+"\\s+");
于 2011-03-16T15:56:32.420 回答
0

Is "little pig" constantly terminated by any other character like space or linefeed? Then you might add this to the pattern.

String pattern = "(little pig)[ \\r\\n]+";
于 2011-03-16T08:05:09.990 回答
0
String poet = "3 little pigs built houses and 1 little pig went to the market";
Pattern p = Pattern.compile("(little pig)\\B");
Matcher m = p.matcher(poet);
List<String> idx = new ArrayList<String>();
idx.add(m.group());
System.out.println(idx);
于 2011-03-16T08:24:29.443 回答
0

这个模式如何匹配任何little pig只包含一次字符串的行:

^.*little pig.*$

其中包含:

  • ^行首
  • .*零个或多个字符
  • $行结束
于 2011-03-16T08:11:33.673 回答