The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util.regex  [26 examples] > Flags  [3 examples]

e433. 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 e436 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

 Related Examples
e434. Adding Comments to a Regular Expression
e435. Compiling a Pattern with Multiple Flags

See also: Groups    Lines    Paragraphs    Searching and Replacing    Tokenizing   


© 2002 Addison-Wesley.