如何找到一個單詞的每個出現?
下面的例子演示了如何使用Pattern.compile()方法和m.group()方法找到一個詞出現次數。
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String args[]) throws Exception { String candidate = "this is a test, A TEST."; String regex = "\ba\w*\b"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(candidate); String val = null; System.out.println("INPUT: " + candidate); System.out.println("REGEX: " + regex + " "); while (m.find()) { val = m.group(); System.out.println("MATCH: " + val); } if (val == null) { System.out.println("NO MATCHES: "); } } }
上面的程式碼範例將產生以下結果。
INPUT: this is a test ,A TEST. REGEX: \ba\w*\b MATCH: a test MATCH: A TEST