天天看点

Java正则表达式的简单介绍以及使用

正则表达式主要是为了方便我们提取一个字符串中感兴趣的部分,尤其在爬虫中应用广泛。我们下面就简单介绍一下其用法。并不做深入研究,只是介绍其使用的方法。

1、matches方法的介绍

这个方法主要是确定给定的字符串是否由你给定的规则组成,什么意思呢。打个比方,

I am Chinese

,这句话是不是由

英文字母+空格组成

。所以他的正则字符串就是

"(\\w+ *)+"

(注意中间有个空格,且由于最后一个字符后面没有空格,所以要用

*

进行匹配,表示可以没有或者有多个)。这个方法要求完全匹配。

这个方法返回的是一个Boolean值,具体用法:

public class Test01 {
    public static void main(String[] args) {
        String string = "123456789abc";
        String regex2 = "(\w+ *)+";
        //方式一
        boolean matches = string.matches(regex2);
        System.out.println("matches = " + matches);

		//方式二
        boolean matches5 = Pattern.matches(regex2, string);
        System.out.println("matches5 = " + matches5);

		//方式三
        Pattern compile = Pattern.compile(regex2);
        Matcher matcher = compile.matcher(string);
        boolean matches6 = matcher.matches();
        System.out.println("matches6 = " + matches6);
    }
}
           

2、find用法

这个就是matches方法的宽松版,不要求完全匹配,只要求包含就可以,类似于contains方法。

Pattern compile = Pattern.compile(regex2);
Matcher matcher = compile.matcher(string);
boolean matches = matcher.matches();
           

3、如何提取我们感兴趣的字符串呢

使用group

测试字符串

str = “I am Chinese 我为武汉加油”

,提取其中的中文字符。

public class Test03 {
    public static void main(String[] args) {
        String str = "I am Chinese 我为武汉加油";
        String regex = "[\\u4e00-\\u9fa5]+";
        Matcher matcher = Pattern.compile(regex).matcher(str);
        //必须先执行这条语句,否则直接执行matcher.group()会一直报错
        boolean isFind = matcher.find();  
        if (isFind){  //建议先进行查找,如果找到了就取出找到的字符串,找不到的话执行.group会报错
            String group = matcher.group();
            System.out.println("group = " + group);
        }
    }
}