[英]Regular expression wtih an escaped closing bracket at the end
这是一个Java /正则表达式问题。
我喜欢使用以下代码段在Java程序的文本字符串中搜索"M(x)"
:
public static List<String> findPattern(String patternStr, String value)
{
ArrayList<String> matchedStrings = new ArrayList<String>(5);
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(value);
while (matcher.find()) {
matchedStrings.add(matcher.group(0));
}
return matchedStrings;
}
以下模式字符串有效:
M\\\\(x\\\\)
以下模式没有:
\\\\bM\\\\(x\\\\)\\\\b
我喜欢使用\\\\b
以便找到文本为"M(x) = abc"
而不是"TM(x) = abc"
的匹配项。 真的很有趣,在进行了所有测试之后, "\\\\b"
似乎只有在前面的字符是转义括号时才会失败。
我有做错什么吗? 还是有可以实现相同目标的东西?
谢谢并恭祝安康
请参阅\\ b是单词边界锚 。 换句话说,它在单词字符(字母,数字,下划线)和非单词字符(其余)之间标记了一个位置。
关键是,')'和''(空格字符)都是非单词字符,因此它们之间没有单词边界。 如果您期望在您的模式中使用它,它将失败。
因此,您可以从模式中删除尾随\\ b,将其变成...
\\bM\\(x\\)
结尾\\b
在您的情况下不起作用,因为\\b
匹配:
如果字符串中的最后一个字符是单词字符,则在字符串的最后一个字符之后。 ( http://www.regular-expressions.info/wordboundaries.html )
为什么需要第二个\\b
? 您可以提供不同的测试用例和预期结果吗?
试试这个.*?(M\\(x\\))
。 .*?
表示非贪婪匹配。
String txt="sdda2asddaTM(x) = abcsdssdcxc";
Pattern p = Pattern.compile(".*?(M\\(x\\))", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(txt);
if (m.find()) {
System.out.print(m.group(1));
}
您不会得到TM(x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.