試試這個:
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));
}
確實要算這是目前內部的兩個打招呼的爲XYZ? –
是否確定xyz會在Hello之間發生? – Arjit