Setting Case Sensitivity in a Regular Expression - Java Regular Expressions

Java examples for Regular Expressions:Pattern

Description

Setting Case Sensitivity in a Regular Expression

Demo Code

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

  public void m() {
    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
  }/*from  w w w . j  a  v a 2s .  c  o m*/
}

Related Tutorials