Friday, October 9, 2015

Case-insensitive regular expression in Java

The java.util.regex.Pattern has several flags which are very helpful.  One of them is CASE_INSENSITIVE

Just add this flag when creating pattern instance.  Everything else follows normal regex usage.

Here is a hello world level demo for case-insensitive regular expression in Java.

package com.shengwang.demo;

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

public class RegexCaseInsensitive {

public static void main(String[] args) {
String input = "ABC";
String regex = "abc";
boolean matchResult;
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); // add flag here
Matcher m = p.matcher(input);
matchResult = m.matches();
System.out.println("matchResult="+matchResult); // print "matchResult=true"
}
}
In fact case-insensitive regular expression can also be enable by add embedded flag expression(?i). But I personally prefer using Pattern.CASE_INSENSITIVE flag for code readability.

For most basic regular expression Java API usage, check out article “The basic regular expression API in Java

0 comments:

Post a Comment

Powered by Blogger.

About The Author

My Photo

Has been a senior software developer, project manager for 10+ years. Dedicate himself to Alcatel-Lucent and China Telecom for delivering software solutions.

Pages

Unordered List