Regex正規表示式都是大小寫敏感的,例如
String str1 = new String("This is an apple");
String regex1 = "APPLE";
Pattern pattern1 = Pattern.compile(regex1);
Matcher matcher1 = pattern1.matcher(str1);
System.out.println(matcher1.find()); // false
String regex2 = "apple";
Pattern pattern2 = Pattern.compile(regex2);
Matcher matcher2 = pattern2.matcher(str1);
System.out.println(matcher2.find()); // true
字串str1中的apple是小寫的,所以regex必須是小寫的才會批配,如果要忽略大小寫敏感的話,可在regex前加上(?i)
即可忽略大小寫。
String str1 = new String("This is an apple");
String regex1 = "(?i)APPLE";
Pattern pattern1 = Pattern.compile(regex1);
Matcher matcher1 = pattern1.matcher(str1);
System.out.println(matcher1.find()); // true
或是在Pattern.compile()
方法中加入第二個參數Pattern.CASE_INSENSITIVE
即可忽略大小寫。
String str1 = new String("This is an apple");
String regex1 = "APPLE";
Pattern pattern1 = Pattern.compile(regex1, Pattern.CASE_INSENSITIVE);
Matcher matcher1 = pattern1.matcher(str1);
System.out.println(matcher1.find()); // true
沒有留言:
張貼留言