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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button