Java正则表达式

前言

关于正则表达式这东西,不用多说,大家都知道,主要用来做校验匹配。这里主要讲Java中正则表达式的用法,也就是Pattern、Matcher的主要用法。代码很简单,一看就懂。

用法

package test;

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

public class Test {

     public static void main(String[] args) {
          String str = "abc12dd354fdfdf1.26fds";
          String reg = "\\d+";

          // 完全匹配,也就是字符串与正则完全匹配
          // 字符串自带的matches方法
          boolean matches1 = str.matches(reg);
          // 相当于
          boolean matches2 = Pattern.matches(reg, str);
          // 也相当于
          boolean matches3 = Pattern.compile(reg).matcher(str).matches();

          // 部分匹配,即字符串中有满足正则的就匹配
          Pattern pattern = Pattern.compile(reg);
          Matcher matcher = pattern.matcher(str);
          while(matcher.find()){   
              // 匹配到的字符串的开始下标
              int start = matcher.start();
              // 匹配到的字符串的结束下标
              int end = matcher.end();
              // 匹配的字符串
              String group = matcher.group();       
              // 注意这里的下标是前闭后开的,也就是start<=index<end
              System.out.println(group  + "      位于下标start:"+start+"   end:"+end); 
          }
    }
}

了解到上面的方式之后,可以做的东西就很多了, 比如找到匹配的字符串之后,替换成xx,或者拼接xx之类的处理,自由想象

false false false

12      位于下标start:3   end:5
354      位于下标start:7   end:10
1      位于下标start:15   end:16
26      位于下标start:17   end:19

为什么说

boolean matches1 = str.matches(reg);
相当于
boolean matches2 = Pattern.matches(reg, str);

开始只是猜想,后面查看String源码matches方法,可以看到:

    public boolean matches(String regex) {
        return Pattern.matches(regex, this);
    }

所以说还是猜对了。然后继续看Pattern.matches方法

    public static boolean matches(String regex, CharSequence input) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        return m.matches();
    }

明白了吧,其实平时用的字符串的匹配,实现也是Pattern、Matcher提供的。

既然看了String的源码,那么继续分析一下,

public String[] split(String regex) {
   return split(regex, 0);
}

String平时使用的很多的split方法,继续追踪下去,代码中间部分就不用看了,就是对字符串的一些处理,最后调用的是Pattern.compile(regex).split(this, limit);

public String[] split(String regex, int limit) {
        char ch = 0;
        if (((regex.value.length == 1 &&
             ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
             (regex.length() == 2 &&
              regex.charAt(0) == '\\' &&
              (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
              ((ch-'a')|('z'-ch)) < 0 &&
              ((ch-'A')|('Z'-ch)) < 0)) &&
            (ch < Character.MIN_HIGH_SURROGATE ||
             ch > Character.MAX_LOW_SURROGATE))
        {
            int off = 0;
            int next = 0;
            boolean limited = limit > 0;
            ArrayList<String> list = new ArrayList<>();
            while ((next = indexOf(ch, off)) != -1) {
                if (!limited || list.size() < limit - 1) {
                    list.add(substring(off, next));
                    off = next + 1;
                } else {    // last one
                    //assert (list.size() == limit - 1);
                    list.add(substring(off, value.length));
                    off = value.length;
                    break;
                }
            }
            // If no match was found, return this
            if (off == 0)
                return new String[]{this};

            // Add remaining segment
            if (!limited || list.size() < limit)
                list.add(substring(off, value.length));

            // Construct result
            int resultSize = list.size();
            if (limit == 0)
                while (resultSize > 0 && list.get(resultSize - 1).length() == 0)
                    resultSize--;
            String[] result = new String[resultSize];
            return list.subList(0, resultSize).toArray(result);
        }
        return Pattern.compile(regex).split(this, limit);
    }

平时看源码看得少,不看不知道,一看吓一跳,其实很多实现都是很多自己用过得东西组装实现的,

比如substring以前有时候substring之后,忘记用字符串接收了,导致没有截取成功,以为调用了就自动截取了,结果发现,它的实现竟然是这样的,难怪

public String substring(int beginIndex, int endIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
    }
    if (endIndex > value.length) {
        throw new StringIndexOutOfBoundsException(endIndex);
    }
    int subLen = endIndex - beginIndex;
    if (subLen < 0) {
        throw new StringIndexOutOfBoundsException(subLen);
    }
    return ((beginIndex == 0) && (endIndex == value.length)) ? this
            : new String(value, beginIndex, subLen);
}

哈哈哈,还是不分析了,继续分析这篇就成了String源码分析了,多看看源码其实可以发现很多东西。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值