Java 中正则表达式如何匹配竖线(|) , 以及在 Kotlin 中是如何改进的?

本文介绍了在Java和Kotlin中如何正确地使用正则表达式来匹配竖线字符(|)。详细解释了Java中String.split方法的内部实现,并展示了如何通过转义字符来匹配竖线。同时对比了Kotlin对此功能的简化处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java 中正则表达式如何匹配竖线(|)

在Java中直接调用String的split方法:

    val b = java.lang.String(a)
    val s3 = b.split("|") // ["a","b","c","|","1","2","3","4"]
    println(JSON.toJSONString(s3))

因为 | 在正则表达式中是或的概念,要想匹配就得用转移字符 "|" 但是 "" 又是java的转移字符,要让其在正则中起作用,就得使用: "\|"

    val b = java.lang.String(a)
    val s3 = b.split("|")
    println(JSON.toJSONString(s3)) // ["a","b","c","|","1","2","3","4"]
    val s4 = b.split("\\|")
    println(JSON.toJSONString(s4)) // ["abc","1234"]

这个Java 中的 split 方法设计简直就是一个"天坑"(天然的坑): 如果不看实现代码,很容易犯错.

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

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.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);
    }

在Kotlin 中, 直接优化了这个 split 方法:

    val a = "abc|1234"

    val s1 = a.split("|")
    val s2 = a.split("\\|")

    println(s1) // [abc, 1234]
    println(s2) // [abc|1234]

Kotlin 开发者社区

国内第一Kotlin 开发者社区公众号,主要分享、交流 Kotlin 编程语言、Spring Boot、Android、React.js/Node.js、函数式编程、编程思想等相关主题。

1233356-bca93e5c34975635

Kotlin 开发者社区

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI天才研究院

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值