本示例说明如何将量词附加到字符类或捕获正则表达式中的组。
package org.nhooo.example.regex;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class CombineWithQuantifier {
public static void main(String[] args) {
// [abc]{3} --> apply quantifier in character class.
// 连续查找“ a”或“ b”或“ c”。
//
// (abc){3} --> apply quantifier in capturing group.
// 连续三遍查找“ abc”。
//
// abc{3} --> apply quantifier in character class.
// 连续三遍查找字符“ c”。
String[] regexs = {"[abc]{3}", "(abc){3}", "abc{3}"};
String text = "abcabcabcabcaba";
for (String regex : regexs) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
// 查找每个匹配并打印
System.out.format("Regex: %s %n", regex);
while (matcher.find()) {
System.out.format("Text \"%s\" found at %d to %d.%n",
matcher.group(), matcher.start(),
matcher.end());
}
System.out.println("------------------------------");
}
}
}该程序将打印以下输出:
Regex: [abc]{3}
Text "abc" found at 0 to 3.
Text "abc" found at 3 to 6.
Text "abc" found at 6 to 9.
Text "abc" found at 9 to 12.
Text "aba" found at 12 to 15.
------------------------------
Regex: (abc){3}
Text "abcabcabc" found at 0 to 9.
------------------------------
Regex: abc{3}
------------------------------