[String源码]Java String.split()源码分析

版权声明:转载著名出处 https://blog.csdn.net/gcola007/article/details/82977139

今天遇到了String.split()方法,结合源码分析、记录下(最后附上正则表达式记录):
知乎专栏:String源码分析

简介

split(String regex, int limit)一般根据正则表达式分割字符串,limit限定分割后的子字符串个数,超过数量限制的情况下前limit-1个子字符串正常分割,最后一个子字符串包含剩下所有字符。重载方法split(String regex)limit设置为0。

    public String[] split(String regex) {
        return split(regex, 0);  //将limit设置为0
    }

split()首先判断传入的regex是否为一些特殊情况:

  • 单字符情况下regex不等于正则表达式的元字符(meta character):.$|()[{^?*+\\
  • 双字符情况下regex第一个字符是反斜杠,第二个字符不是Unicode编码中的数字或字母

特殊情况下split()直接进行分割处理,没有涉及到PatternMatcher类。源码如下:

    public String[] split(String regex, int limit) {
        /* fastpath if the regex is a
         (1)one-char String and this character is not one of the
            RegEx's meta characters ".$|()[{^?*+\\", or
         (2)two-char String and the first char is the backslash and
            the second is not the ascii digit or ascii letter.
         */
        char ch = 0;
        if (((regex.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);
                    int last = length();
                    list.add(substring(off, last));
                    off = last;
                    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, 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);
    }

源码分析

特殊情况判断
 if (((regex.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))
  • regex长度为1时,将regex赋给ch,判断ch是否在.$|()[{^?*+\\
  • regex长度为2时,第一个字符为\\(要表示一个\需要用两个\\转义得到),第二个字符不在0-9,a-z,A-Z中,且不在Unicode编码的\uD800-\uDBFF之间。\uD800-\uDBFF区间表示的是UTF-16中的低代理项,具体代表字符可以去编码表自行查看。源码如下:
    /**
     * The minimum value of a
     * <a href="http://www.unicode.org/glossary/#high_surrogate_code_unit">
     * Unicode high-surrogate code unit</a>
     * in the UTF-16 encoding, constant {@code '\u005CuD800'}.
     * A high-surrogate is also known as a <i>leading-surrogate</i>.
     *
     * @since 1.5
     */
    public static final char MIN_HIGH_SURROGATE = '\uD800';
    public static final char MAX_HIGH_SURROGATE = '\uDBFF';
字符串分割

第一次分割时,使用offnextoff指向每次分割的起始位置,next指向分隔符的下标,完成一次分割后更新off的值,当list的大小等于limit-1时,直接添加剩下子字符串。

  • 如果字符串不含分隔符,直接返回原字符串。
  • 如果字符串第一次分割完后没有数量没有达到limit-1,最终余下的字符串在第二次被添加。
  • limit等于0的情况下,从最后一个子字符串往前数,所有的空字符串""都会被清除
调用正则匹配

split()方法在非特殊情况情况下是调用java.util.regex目录下主要的两个类PatternMatcher进行分割处理的。String中涉及到正则匹配都是通过这两个类实现的。
Pattern类是理解为模式类,创建一个匹配模式,构造方法私有,不可以直接创建,但可以通过Pattern.complie(String regex)简单工厂方法创建一个正则表达式。
Matcher类是匹配器类,是用来解释Pattern对character sequence执行匹配操作的引擎,构造方法也是私有的,只能通过Pattern.matcher(CharSequence input)方法得到该类的实例

调用流程
    return Pattern.compile(regex).split(this, limit);

调用Pattern类中的静态方法构造一个模式类

    public static Pattern compile(String regex, int flags) {
        return new Pattern(regex, flags);
    }

接着调用Pattern.split()方法,在这个方法中调用matcher方法返回一个Mathcer对象m,与String.split()中特殊情况的处理过程类似。

  • 使用m.find()m.start()m.end方法。
  • 每找到一个分隔符,更新start和end的位置。
  • 处理没找到分隔符、子字符串数量小于limit以及limit=0的情况。
    源码如下
    public String[] split(CharSequence input) {
        return split(input, 0);
    }

    public String[] split(CharSequence input, int limit) {
        int index = 0;
        boolean matchLimited = limit > 0;
        ArrayList<String> matchList = new ArrayList<>();
        Matcher m = matcher(input);

        // Add segments before each match found
        while(m.find()) {
            if (!matchLimited || matchList.size() < limit - 1) {
                if (index == 0 && index == m.start() && m.start() == m.end()) {
                    // no empty leading substring included for zero-width match
                    // at the beginning of the input char sequence.
                    continue;
                }
                String match = input.subSequence(index, m.start()).toString();
                matchList.add(match);
                index = m.end();
            } else if (matchList.size() == limit - 1) { // last one
                String match = input.subSequence(index,
                                                 input.length()).toString();
                matchList.add(match);
                index = m.end();
            }
        }

        // If no match was found, return this
        if (index == 0)
            return new String[] {input.toString()};

        // Add remaining segment
        if (!matchLimited || matchList.size() < limit)
            matchList.add(input.subSequence(index, input.length()).toString());

        // Construct result
        int resultSize = matchList.size();
        if (limit == 0)
            while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
                resultSize--;
        String[] result = new String[resultSize];
        return matchList.subList(0, resultSize).toArray(result);
    }
小结

事实上,PatternMatcher的源码还有很多东西,这里只是浅尝辄止,等String类研究明白再看吧。除了split()方法外,有正则表达式接口的方法都是调用模式类和匹配器类进行实现的。
JDK源码的每一个如finalprivate的关键字都设计的十分严谨,多读注释,多注意这些细节对于阅读代码和自己写代码都有很大的帮助。

附正则表达式用法:
字符类匹配

[…] 查找方括号之间的任何字符
[^…] 查找任何不在方括号之间的字符
[a-z] 查找任何从小写 a 到小写 z 的字符
[A-Z] 查找任何从大写 A 到大写 Z 的字符
[A-z] 查找任何从大写 A 到小写 z 的字符
. 查找单个字符,除了换行和行结束符
\w 查找单词字符,等价于[a-zA-Z0-9]
\W 查找非单词字符,等价于[^a-zA-Z0-9]
\s 查找空白字符
\S 查找非空白字符
\d 查找数字,等价于[0-9]
\D 查找非数字字符,等价于[^0-9]
\b 匹配单词边界
\r 查找回车符
\t 查找制表符
\0 查找 NULL 字符
\n 查找换行符

重复字符匹配

{n,m} 匹配前一项至少n次,但不能超过m次
{n,} 匹配前一项n次或更多次
{n} 匹配前一项n次
n? 匹配前一项0次或者1次,也就是说前一项是可选的,等价于{0,1}
n+ 匹配前一项1次或多次,等价于{1,}
n* 匹配前一项0次或多次,等价于{0,}
n$ 匹配任何结尾为 n 的字符串
^n 匹配任何开头为 n 的字符串
?=n 匹配任何其后紧接指定字符串 n 的字符串
?!n 匹配任何其后没有紧接指定字符串 n 的字符串

匹配特定数字

^[1-9]\d*$    匹配正整数
^-[1-9]\d*$   匹配负整数
^-?[0-9]\d*$   匹配整数
^[1-9]\d*|0$  匹配非负整数(正整数 + 0)
^-[1-9]\d*|0$   匹配非正整数(负整数 + 0)
^[1-9]\d*.\d*|0.\d*[1-9]\d*$  匹配正浮点数
^-([1-9]\d*.\d*|0.\d*[1-9]\d*)$ 匹配负浮点数
^-?([1-9]\d*.\d*|0.\d*[1-9]\d*|0?.0+|0)$  匹配浮点数
^[1-9]\d*.\d*|0.\d*[1-9]\d*|0?.0+|0$   匹配非负浮点数(正浮点数 + 0)
^(-([1-9]\d*.\d*|0.\d*[1-9]\d*))|0?.0+|0$  匹配非正浮点数(负浮点数 + 0)

匹配特定字符串

^[A-Za-z]+$ 匹配由26个英文字母组成的字符串
^[A-Z]+$  匹配由26个英文字母的大写组成的字符串
^[a-z]+$  匹配由26个英文字母的小写组成的字符串
^[A-Za-z0-9]+$  匹配由数字和26个英文字母组成的字符串
^\w+$  匹配由数字、26个英文字母或者下划线组成的字符串


简书地址:[String源码]Java String.split()源码分析
欢迎交流,关注。

猜你喜欢

转载自blog.csdn.net/gcola007/article/details/82977139