无法弄清楚如何将短语字符串与文件流中的短语进行匹配。我正在处理的文件包含随机单词,例如:
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()
或 matcher.matches()
但当我不能依赖我匹配的文件字符串短语位于单独的行时,我不知道如何设置正确的区域。
“小猪”是否经常被任何其他字符(例如空格或换行符)终止?然后你可以将其添加到模式中。
String pattern = "(little pig)[ \\r\\n]+";
这个模式怎么样,它只匹配包含字符串
little pig
的任何行一次:
^.*little pig.*$
其中包含:
^
行首.*
零个或多个字符$
行尾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);
编辑4(最后一个):完全忘记一开始需要
\\s|^
编辑 3:做了一些调整,考虑到 searchString 之后的字符可能是字符串的结尾
search P = Pattern.compile("\\s"+Pattern.quote(searchString)+"(\\s|$)");
编辑2:好的,我明白了!
searchP = Pattern.compile("\\s"+Pattern.quote(searchString)+"\\s");
不知道为什么我没有注意到引用方法...哦,一切都是第一次:)
编辑:事实证明我有点超前了 - 代码对于特殊字符根本没有帮助,因为在 searchP 中将literalP 转换为 String 并丢失了用户 String 的
LITERAL
规则。
我想我明白了!下面将用户的字符串转换为文字,然后将其放入允许
\\s
的新模式中。如果有人发现问题,请告诉我。
Pattern literalP = Pattern.compile(searchString, Pattern.LITERAL);
Pattern searchP = Pattern.compile("\\s"+literalPattern+"\\s+");