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().

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/

上一篇: Many chromedriver.exe are left hanging on Windows Selenium
下一篇: Jackson : was expecting double-quote to start field name
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号