Setting Case Sensitivity in a Regular Expression

By default, a pattern is case-sensitive. By adding a flag, a pattern can be made case-insensitive.

It is also possible to control case sensitivity within a pattern using the inline modifier (?i). The inline modifier affects all characters to the right and in the same enclosing group, if any. For example, in the pattern a(b(?i)c)d, only c is allowed to be case-insensitive. You can also force case sensitivity with (?-i).

The inline modifier can also contain pattern characters using the form (?i:abc). In this case, only those pattern characters inside the inline modifier's enclosing group are affected. This form does not capture text (see Capturing Text in a Group in a Regular Expression).

CharSequence inputStr = "Abc"; String patternStr = "abc"; // Compile with case-insensitivity Pattern pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); boolean matchFound = matcher.matches(); // true // Use an inline modifier matchFound = pattern.matches("abc", "aBc"); // false matchFound = pattern.matches("(?i)abc", "aBc"); // true matchFound = pattern.matches("a(?i)bc", "aBc"); // true // Use enclosing form matchFound = pattern.matches("((?i)a)bc", "aBc"); // false matchFound = pattern.matches("(?i:a)bc", "aBc"); // false matchFound = pattern.matches("a((?i)b)c", "aBc"); // true matchFound = pattern.matches("a(?i:b)c", "aBc"); // true // Use a character set matchFound = pattern.matches("[a-c]+", "aBc"); // false matchFound = pattern.matches("(?i)[a-c]+", "aBc"); // true

Comments

14 Jan 2010 - 4:01am by Anonymous (not verified)

I been searching for this for months.....Exellent...Thanks mate!

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.