Search code examples
javaregexstringsyntaxcase-insensitive

Java Case Insensitive Method Breakdown and Explanation


public class StringMatchesCaseInsensitive
{
   public static void main(String[] args)
   {
      String stringToSearch = "Four score and seven years ago our fathers ...";

      // this won't work because the pattern is in upper-case
      System.out.println("Try 1: " + stringToSearch.matches(".*SEVEN.*"));

      // the magic (?i:X) syntax makes this search case-insensitive, so it returns true
      System.out.println("Try 2: " + stringToSearch.matches("(?i:.*SEVEN.*)"));
   }
}

The code block above is what it is; an example of a case-insensitive search. But what I'm most interested in is this : "?i:.*SEVEN.*";.

I know that ?:. is the case-insensitive syntax. But what about the .* that encapsulates SEVEN? What does it do?

Where can I read more about the ., *, and .* regex modifiers?

Thanks in advance


Solution

  • Following is what those symbols stand for.

    • . stands for any character except the newline. If used with s flag then it matches newline too.

    • * is quantifier which says zero or many.

    • .* will say zero or many characters.

    You can read more about them on