1 import java.util.regex.Matcher; 2 import java.util.regex.Pattern; 3 4 //已知一段英文,查找裏面由三個字母構成的單詞的個數 5 public class redex1 { 6 public static void main(String[] args) { 7 String s="IT is within my memory that Melville Clarendon, a lad of sixteen years, was riding through Southern Minnesota, in company with his sister Dorothy, a sweet little miss not quite half his own age."; 8 //定義正則表達式,即3個字母而且兩邊是邊界 9 String redex="\\b\\w{3}\\b"; 10 Pattern p=Pattern.compile(redex); 11 Matcher m=p.matcher(s); 12 while (m.find()){ 13 System.out.println(m.group()); 14 } 15 16 } 17 }
結果:java