Java正则表达式

来源:互联网 发布:淘宝竹筒粽子的竹筒 编辑:程序博客网 时间:2024/06/08 18:57

前言

关于正则表达式这东西,不用多说,大家都知道,主要用来做校验匹配。这里主要讲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 false12      位于下标start:3   end:5354      位于下标start:7   end:101      位于下标start:15   end:1626      位于下标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
原创粉丝点击