java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java正则表达式匹配规则

java正则表达式匹配规则超详细总结

作者:SmarTongs

正则表达式并不仅限于某一种语言,但是在每种语言中有细微的差别,下面这篇文章主要给大家介绍了关于java正则表达式匹配规则的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下

1 单个字符的匹配规则如下:

2 多个字符的匹配规则如下:

3 复杂匹配规则主要有:

4 提取匹配的字符串子段

Pattern p = Pattern.compile("(\\d{3,4})\\-(\\d{7,8})");
Matcher m = p.matcher("010-12345678");

正则表达式用(...)分组可以通过Matcher对象快速提取子串:
- group(0)表示匹配的整个字符串;
- group(1)表示第1个子串,group(2)表示第2个子串,以此类推。

5 非贪婪匹配

用表达式

(\d+)(0*)

去匹配123000,10100,1001结果都是\d+匹配到所有字符而0*未用到,因为正则表达式默认采取贪婪匹配策略(匹配尽可能多的字符),在\d+后边加个?就表示非贪婪(匹配尽可能少的字符),非贪婪如下:

(\d+?)(0*)

6 替换和搜索

6.1 分割字符串

对输入的不规则字符串利用string.split()传入正则表达式提取想要的部分:

"a b c".split("\\s"); // { "a", "b", "c" }
"a b  c".split("\\s"); // { "a", "b", "", "c" }
"a, b ;; c".split("[\\,\\;\\s]+"); // { "a", "b", "c" }

6.2 搜索字符串

public class Main {
    public static void main(String[] args) {
        String s = "the quick brown fox jumps over the lazy dog.";
        Pattern p = Pattern.compile("\\wo\\w");
        Matcher m = p.matcher(s);
        while (m.find()) {
            String sub = s.substring(m.start(), m.end());
            System.out.println(sub);
        }
    }
}

output:

row
fox
dog

6.3 替换字符串

使用正则表达式替换字符串可以直接调用String.replaceAll(),它的第一个参数是正则表达式,第二个参数是待替换的字符串。我们还是来看例子:

public class Main {
    public static void main(String[] args) {
        String s = "The     quick\t\t brown   fox  jumps   over the  lazy dog.";
        String r = s.replaceAll("\\s+", " ");
        System.out.println(r); // "The quick brown fox jumps over the lazy dog."
    }
}

6.4 反向引用

如果我们要把搜索到的指定字符串按规则替换,比如前后各加一个xxxx,这个时候,使用replaceAll()的时候,我们传入的第二个参数可以使用$1、$2来反向引用匹配到的子串。例如:

public class Main {
    public static void main(String[] args) {
        String s = "the quick brown fox jumps over the lazy dog.";
        String r = s.replaceAll("\\s([a-z]{4})\\s", " <b>$1</b> ");
        System.out.println(r);
    }
}

output

the quick brown fox jumps <b>over</b> the <b>lazy</b> dog.

总结 

到此这篇关于java正则表达式匹配规则的文章就介绍到这了,更多相关java正则表达式匹配规则内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文