我有一条前线 HelloxyzxyzxyzHello
我有一个以下正则表达式匹配此行
Map<Character, Integer> map = new HashMap();
for (char c: cs) {
Integer iCnt = map.get(c);
if (iCnt == null) {
map.put(c, 1);
} else {
map.put(c, ++iCnt);
}
}
现在我想得到xyz的数量 在我的行中它是3
除了查找每个匹配的模式并使用计数器之外,是否有可从regex获得的现成API。
答案 0 :(得分:1)
试试这个:
import java.util.regex.*;
class Test {
public static void main(String[] args) {
String hello = "HelloxyzxyzxyzHello";
Pattern pattern = Pattern.compile("xyz");
Matcher matcher = pattern.matcher(hello);
int count = 0;
while (matcher.find())
count++;
System.out.println(count); // prints 3
}
}
编辑:捕获群组
String line = "This order was placed for QT3000! OK?";
Pattern pattern = Pattern.compile("(.*?)(\\d+)(.*)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
System.out.println("group 1: " + matcher.group(1));
System.out.println("group 2: " + matcher.group(2));
System.out.println("group 3: " + matcher.group(3));
}
答案 1 :(得分:1)
您可以尝试使用以下正则表达式来获取两个xyz
子字符串中存在的所有Hello
计数。
import java.util.regex.*;
class Test {
public static void main(String[] args) {
String hello = "HelloxyzxyzxyzHello";
Pattern pattern = Pattern.compile("(?:Hello|(?<!^)\\G)(?:(?!Hello).)*?(xyz)(?=.*?Hello)");
Matcher matcher = pattern.matcher(hello);
int count = 0;
while (matcher.find()) {
if (matcher.group(1)) {
count++;
}
}
System.out.println(count); // prints 3
}
}