Main Tutorials

Regular Expression case sensitive example – Java

In Java, by default, the regular expression (regex) matching is case sensitive. To enable the regex case insensitive matching, add (?) prefix or enable the case insensitive flag directly in the Pattern.compile().

A regex pattern example.


Pattern = Registrar:\\s(.*)

Case Insensitive, add (?) prefix.


Pattern = (?)Registrar:\\s(.*)

Case Insensitive, add Pattern.CASE_INSENSITIVE flag.


Pattern.compile("Registrar:\\s(.*)", Pattern.CASE_INSENSITIVE);

1. RegEx Example

Example to use regex case insensitive matching to get the “Registrar” information.


package com.mkyong.regex

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

public class RunExampleTest{
	
	private Pattern registrarPattern = Pattern.compile(REGISTRAR_PATTERN);
	
	//alternative
	/*private Pattern registrarPattern = 
		Pattern.compile(REGISTRAR_PATTERN, Pattern.CASE_INSENSITIVE);*/
	
	private Matcher matcher;

	private static final String REGISTRAR_PATTERN = "(?)Registrar:\\s(.*)";
	
	public static void main(String[] args) {
	
		String data = "Testing... \n" +
			"Registrar: abc.whois.com\n" +
			"registrar: 123.whois.com\n" +
			"end testing";
		
		RunExampleTest obj = new RunExampleTest();
		List<String> list = obj.getRegistrar(data);
		
		System.out.println(list);
		
	}
	
	private List<String> getRegistrar(String data){
		
		List<String> result = new ArrayList<String>();
		
		matcher = registrarPattern.matcher(data);

		while (matcher.find()) {
			result.add(matcher.group(1));
		}
		
		return result;
	}
	
}

Output


[abc.whois.com, 123.whois.com]
Note
If the (?) is deleted, only the [abc.whois.com] will be returned. (Case sensitive).

References

  1. Wikipedia : Case Sensitivity
  2. Wikipedia : Regular Expression/

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
ztomic
10 years ago

This is wrong 🙂
Flag for case insensitive matching is (?i), not (?) (see: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#CASE_INSENSITIVE)

Output of your example will be:
[abc.whois.com]
with or without (?)

Andrew
3 years ago
Reply to  ztomic

Thanks a lot for (?i)
cheers!

jivraj
8 years ago

Thanka a lot ..+1 for Pattern.CASE_INSENSITIVE
cheers!