简体   繁体   English

如何使用Java分割带有特殊字符的字符串

[英]How to split String with special character using Java

What is the way, how to split String with special character using Java? 用Java用特殊字符分割String的方式是什么?

I have very simple captcha like this: 我有一个非常简单的验证码,如下所示:

5 + 10 5 + 10

String captcha = "5 + 10";
String[] captchaSplit = captcha.split("+");

And I get error: 我得到错误:

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0 线程“主”中的异常java.util.regex.PatternSyntaxException:靠近索引0的悬挂元字符'+'

How to fix it? 如何解决?

Thank you. 谢谢。

+ is a reserved character in regular expression and split takes regExp as a parameter. +是正则表达式中的保留字符,并且splitregExp作为参数。 You can escape it by \\\\+ which will now match + . 您可以通过\\\\+对其进行转义,现在将匹配+

Type it in square brackets 在方括号中输入

String captcha = "5 + 10";
String[] captchaSplit = captcha.split("[+]");

If you need to split String with multiple special symbols/characters, it's more convenient to use Guava library that contains Splitter class: 如果您需要使用多个特殊符号/字符来拆分String,则使用包含Splitter类的Guava库更加方便:

    @Test
    public void testSplitter() {
        String str = "1***2***3";
        List<String> list = Lists.newArrayList(Splitter.on("***").split(str));
        Assert.assertThat(list.size(), is(3));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM