使用 split("|") 通过管道符号拆分 Java 字符串 [英] Splitting a Java String by the pipe symbol using split("|")

查看:17
本文介绍了使用 split("|") 通过管道符号拆分 Java 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 官方文档指出:

The Java official documentation states:

例如,字符串 "boo:and:foo" 使用这些表达式产生以下结果正则表达式结果:

The string "boo:and:foo", for example, yields the following results with these expressions Regex Result :

{ "boo", "and", "foo" }"

这就是我需要它工作的方式.但是,如果我运行这个:

And that's the way I need it to work. However, if I run this:

public static void main(String[] args){
        String test = "A|B|C||D";

        String[] result = test.split("|");

        for(String s : result){
            System.out.println(">"+s+"<");
        }
    }

它打印:

><
>A<
>|<
>B<
>|<
>C<
>|<
>|<
>D<

这与我的预期相去甚远:

Which is far from what I would expect:

>A<
>B<
>C<
><
>D<

为什么会这样?

推荐答案

您需要

test.split("\\|");

split 使用正则表达式,在 regex| 是表示 OR 运算符的元字符.您需要使用 \ 转义该字符(用 String 编写为 "\\" 因为 \ 也是字符串文字中的元字符,需要另一个\ 转义它).

split uses regular expression and in regex | is a metacharacter representing the OR operator. You need to escape that character using \ (written in String as "\\" since \ is also a metacharacter in String literals and require another \ to escape it).

你也可以使用

test.split(Pattern.quote("|"));

然后让 Pattern.quote 创建表示 | 的正则表达式的转义版本.

and let Pattern.quote create the escaped version of the regex representing |.

这篇关于使用 split("|") 通过管道符号拆分 Java 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆