正则表达式匹配两个特殊字符中间的内容

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xufei512/article/details/82388881

匹配两个字符串A与B中间的字符串包含A与B:
表达式: A.*?B(“.“表示任意字符,“?”表示匹配0个或多个)
示例: Abaidu.comB
结果: Awww.apizl.comB
匹配两个字符串A与B中间的字符串包含A但是不包含B:
表达式: A.*?(?=B)
示例: Awww.apizl.comB
结果: Awww.apizl.com
匹配两个字符串A与B中间的字符串且不包含A与B:
表达式: (?<=A).*?(?=B)
这种写法没看懂,我猜测是如果不包含前面匹配的字符写法(?<=要匹配的开始字符),不包含后面要匹配的字符写法(?=要匹配的结束字符)
示例: Awww.baidu.comB
结果: www.baidu.com

    public static void main(String[] args) {
        String rex = "(?<=当前余额为).*?(?=元)";
        String str = "hffbbcbcvbxnbvb当前余额为38元vnnvcxvcnn";
        Pattern pattern = Pattern.compile(rex);
        Matcher matcher = pattern.matcher(str);
        if(matcher.find()) {
            System.out.println(matcher.group());
        }
        
        String rex2 = "(?<=当前剩余流量为).*?(?=G|g)";
        String str2 = "hffbbcbcvbxnbvb当前剩余流量为1gvnnvcxvcnn";
        Pattern pattern2 = Pattern.compile(rex2);
        Matcher matcher2 = pattern2.matcher(str2);
        if(matcher2.find()) {
            System.out.println(matcher2.group());
        }
    }

输出结果为:

38
1

猜你喜欢

转载自blog.csdn.net/xufei512/article/details/82388881