regex
Case control example
In this example we shall show you how to handle a case control using a class with a regular expression. To use a regular expression to check on a case one should perform the following steps:
- Compile a String regular expression to a Pattern, using
compile(String regex, int flags)
API method of Pattern, with case-insensitive matching. - Compile the same regular expression to a Pattern, using
compile(String regex)
API method of Pattern. This pattern has a case-sensitive matching. - Use
matcher(CharSequence input)
API method of Pattern to create a Matcher that will match the given String input against the first pattern and the second pattern. - Use
lookingAt()
API method of Matcher for both patterns to check if the input String matches the patterns,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Show case control using RE class. */ public class CaseMatch { public static void main(String[] argv) { boolean found; Matcher m; String pattern = "^q[^u]\d+\."; String inputStr = "QA777. is the next flight. It is on time."; Pattern reCaseInsensensitive = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); Pattern reCaseSensensitive = Pattern.compile(pattern); m = reCaseInsensensitive.matcher(inputStr); // will match any case found = m.lookingAt(); // will match any case System.out.println("IGNORE_CASE match " + found); m = reCaseSensensitive.matcher(inputStr); // Get matcher w/o case-insens flag found = m.lookingAt(); // will match case-sensitively System.out.println("MATCH_NORMAL match was " + found); } }
Output:
IGNORE_CASE match true
MATCH_NORMAL match was false
This was an example of a case control in Java.