2011-02-27 96 views
0

我正在尝试在大文本中查找特定短语,但该短语可能包含“[”,“(”,“*”等字符,...如“name1(name2”,但它会导致无效。例外寻找它的时候,这里是我的代码:如何将模式与内部的括号相匹配?

Pattern myPattern = Pattern.compile("\\b" + phrase + "\\b"); // Exception 
Matcher myMatcher = myPattern.matcher(largeText); 

我曾尝试使用引号(...),以解决此类字符,但它没有工作:

phrase = Pattern.quote(phrase); 

哪有我解决这个问题以允许这样的字符?

+0

我认为这是因为这些是字边界字符,所以他们被'\ b'抓住,切断你的匹配? – BoltClock 2011-02-27 09:51:54

+0

您能否详细说明为什么Pattern.quote不起作用?这似乎是在这里使用的优雅解决方案。 – mmccomb 2011-02-27 09:52:25

+0

@BoltClock,像'\ b'这样的锚符合空字符串,它们只用于限制特定位置的模式匹配,但它们不会“消耗”任何东西。 – 2011-02-27 10:00:48

回答

2

Pattern.quote(phrase)作品就好了:

String largeText = "a()b a()c a()b"; 
String phrase = "a()b"; 
Pattern myPattern = Pattern.compile("\\b" + Pattern.quote(phrase) + "\\b"); 
Matcher myMatcher = myPattern.matcher(largeText); 
while(myMatcher.find()) { 
    System.out.println(myMatcher.group()); 
} 

打印:

a()b 
a()b 
+0

..你是对的巴特。使用引号(...)后,我得到了同样的异常,所以我认为这并没有解决它。但在追踪我的代码后,我发现它发生在另一行后...感谢每个人的答案。 – Brad 2011-02-27 13:29:24

+0

@布拉德,不客气。很高兴听到你追踪了这个错误。 – 2011-02-27 13:31:37

0

过程短语来转义所有可能的正则表达式元字符。

0

能否请您提供重现这个问题的完整的例子吗?我试过以下,它工作正常:

String largeText = "large text with name1 (name2) and possibly something more"; 
String phrase = "name1 (name2"; 
phrase = Pattern.quote(phrase); 
Pattern myPattern = Pattern.compile("\\b" + phrase + "\\b"); // Exception 
System.out.println("The pattern is " + myPattern.pattern()); 
Matcher myMatcher = myPattern.matcher(largeText); 
if (myMatcher.find()) { 
    System.out.println("A match is found: " + myMatcher.group()); 
} 

输出是:

The pattern is \b\Qname1 (name2\E\b 
A match is found: name1 (name2 
0

您可能希望只使用:

int offset = largeText.indexOf(phrase); 

测试存在/偏移一个子串。

使用模式,这应该工作:

String longString = "this[that]the other* things"; 
String phrase = "[that]"; 
Pattern myPattern = Pattern.compile("\\b" + Pattern.quote(phrase) + "\\b")); 
Matcher m = myPattern.matcher(longString); 
if (m.find()) { 
    System.out.println(m.group()); 
} 

但在使用时,有一个小问题*和?在短语的开头或结尾。

这些字符被视为空白字符(而不是单词字符),因此如果它们出现在短语的开头或结尾,则匹配边界时必须包含所有前导/尾随空格。

如果短语在开头或结尾处包含这些字符,则可能需要删除“\ b”来解决此问题。

相关问题