-1
String input = "This is a *2*2*2 test";
String input1 = "This is also a *2*2*2*2 test"; 

如何编写捕获 (*2*2*2) 或 (*2*2*2*2) 的正则表达式?

4

2 回答 2

2

你可以试试这个:

Pattern p = Pattern.compile("((\\*2){3,4})");

解释:在模式中\\插入一个单\;这将转义*否则将是通配符匹配的。然后字符序列“*2”精确匹配 3 或 4 次。整个事物周围的括号使它成为一个捕获组。

于 2013-08-16T17:53:35.727 回答
1

你可以试试正则表达式:

(\*2){3,4}

另一方面,您需要使用 Pattern 的常量来避免每次都重新编译表达式,如下所示:

private static final Pattern REGEX_PATTERN = 
        Pattern.compile("(\\*2){3,4}");

public static void main(String[] args) {
    String input = "This is a *2*2*2 or *2*2*2*2 test";
    Matcher matcher = REGEX_PATTERN.matcher(input);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }
}

输出:

*2*2*2
*2*2*2*2
于 2013-08-16T17:53:32.340 回答