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

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

问题描述

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<

这远远超出我的预期:

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

为什么会发生这种情况?

Why is this happening?

推荐答案

你需要

test.split("\\|");

split 使用正则表达式并在 regex | 是表示 OR 运算符的元字符。您需要使用 \ (以字母为单位写入\\来转义该字符,因为 \ 也是字符串文字中的元字符,需要另一个 \ 来转义它。)

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(&quot; |&quot;)按管道符号拆分Java String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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