Java如何使用量词编译字符类?
本示例说明如何将量词附加到字符类或捕获正则表达式中的组。
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}
------------------------------
热门推荐
10 小学毕业父母简短祝福语
11 幼儿生日祝福语模板简短
12 新娘妈妈的祝福语简短
13 邻居聚会祝福语大全简短
14 十条祝福语简短
15 给同学祝福语的简短
16 过年祝福语简短祝妈妈
17 祝女儿简短祝福语大全
18 恩师诗词祝福语简短大全