0

为什么这个 RegEx 不会给我任何结果?!?

Pattern p = Pattern.compile("(^|\\S*\\s)\\S*est\\S*($|\\s\\S*)"); //
Matcher m = p.matcher("this is my test string");
if(m.matches())
   Log.d("TRACE", "result " + m.group());

我在gskinners RegExr中测试了模式,它工作正常,然后我逃避了我认为的正确条款,但它从来没有给我任何结果。

4

2 回答 2

0

您需要在第一组和最后一组之后添加一个+或一个*符号,因为它们可能会重复多次:

Pattern p = Pattern.compile("(^|\\S*\\s)+\\S*est\\S*($|\\s\\S*)+");
Matcher m = p.matcher("this is my test string");
if (m.matches()) {
    System.out.println(m.group());
}
于 2013-10-04T12:04:12.357 回答
0

Matcher.matches()想要匹配整个字符串。如果要匹配字符串的一部分,请使用Matcher.find().

Pattern p = Pattern.compile("(^|\\S*\\s)\\S*est\\S*($|\\s\\S*)"); //
Matcher m = p.matcher("this is my test string");
if(m.find())
   Log.d("TRACE", "result " + m.group());
于 2013-10-04T12:08:12.710 回答