字符串匹配正则表达式需要

时间:2013-02-04 20:07:44

标签: java regex string matcher

我有matcher的java代码,可以使用mattcher.find方法查找字符串中出现的次数。

以下是我的代码

String text = "INCLUDES(ABC) EXCLUDES(ABC) EXCLUDES(ABC) INCLUDES(EFG) INCLUDES(IJK)";

String patternString = "INCLUDES(.)";

Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);

int count = 0;
while(matcher.find()) {
    count++;
    System.out.println("found: " + count + " : "
            + matcher.start() + " - " + matcher.end());
    System.out.println(" - " +text.substring(matcher.start(), matcher.end()));
}

将输出返回为

found: 1 : 0 - 9
 - INCLUDES(
found: 2 : 42 - 51
 - INCLUDES(
found: 3 : 56 - 65
 - INCLUDES(

而不是我希望正则表达式找到并返回出现次数为INCLUDES(*)

任何解决方案都是适用的。预期输出应为循环打印值

INCLUDES(ABC)
INCLUDES(EFG)
INCLUDES(IJK)

1 个答案:

答案 0 :(得分:1)

你的正则表达式不正确。您只是捕获括号内的单个字符,因此您的正则表达式将失败。

尝试使用: -

"\\w+\\(.*?\\)"

然后获取group(0),或仅group(): -

String text = "INCLUDES(ABC) EXCLUDES(ABC) EXCLUDES(ABC) INCLUDES(ABC) INCLUDES(ABC)";
Matcher matcher = Pattern.compile("\\w+\\(.*?\\)").matcher(text);

while (matcher.find()) {
    System.out.println(matcher.group());
}