Regex正則表示式的字符組(character class, or character set)為中括弧[...]包夾的數個字符。
意思是只要符合括弧中的任一字符即匹配。
下面範例的的字符組為[abc],所以只要字串中含有a或b或c任一字元即匹配。(注意這邊的regex前後沒有開頭符號^及結束符號$。)
String regex = "[abc]";
Pattern p = Pattern.compile(regex);
System.out.println(p.matcher("abc").find()); // true
System.out.println(p.matcher("a").find()); // true
System.out.println(p.matcher("ab").find()); // true
System.out.println(p.matcher("bc").find()); // true
System.out.println(p.matcher("cde").find()); // true
System.out.println(p.matcher("00a").find()); // true
System.out.println(p.matcher("123").find()); // false
System.out.println(p.matcher("ef").find()); // false
在字符組中的^代表不包含,也就是字串中若不含有任一字符組中的字元則匹配。
下面範例將前一個範例的[abc]改為[^abc],可以看到若字串中只要不含有a或b或c的字元則匹配。
String regex = "[^abc]";
Pattern p = Pattern.compile(regex);
System.out.println(p.matcher("abc").find()); // false
System.out.println(p.matcher("a").find()); // false
System.out.println(p.matcher("ab").find()); // false
System.out.println(p.matcher("bc").find()); // false
System.out.println(p.matcher("cde").find()); // true 雖然字串中有c,但有不為a或b或c的d及e,所以匹配
System.out.println(p.matcher("00a").find()); // true 雖然字串中有a,但有不為a或b或c的數字0,所以匹配
System.out.println(p.matcher("123").find()); // true
System.out.println(p.matcher("ef").find()); // true
要特別強調的是,正則表示式的某些特殊符號在字符組[...]中的意思和在字符組外的意思並不同,例如^在括弧中([^...])是排除的意思,而在字符組外(^[...])是從字串開頭開始匹配的意思,請參考這篇。又例如.在字符組內代表這個符號本身,而在字符組外代表任一字元皆匹配(wildcard),請參考這篇。
在字符組中可使用減號-來表示一個區間內的字,例如[0-9]的意思同等於[0123456789],[a-e]同等於[abcde]
下面範例的字串如果不含任何一英文或數字,例如字串中只有中文字元或特殊符號,則不匹配。
String regex = "[0-9a-zA-Z]";
Pattern p = Pattern.compile(regex);
System.out.println(p.matcher("中文").find()); // false
System.out.println(p.matcher("!@#$").find()); // false
System.out.println(p.matcher("a中文").find()); // true
System.out.println(p.matcher("99中文").find()); // true
沒有留言:
張貼留言