0

What is the way, how to split String with special character using Java?

I have very simple captcha like this:

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

How to fix it?

Thank you.

cagounai
  • 155
  • 2
  • 9
  • Possible duplicate of [Java Regex, List of all special characters that needs to be escaped in regex](http://stackoverflow.com/questions/14134558/java-regex-list-of-all-special-characters-that-needs-to-be-escaped-in-regex) – Enamul Hassan Nov 29 '15 at 08:53
  • You probably want to split on `" *[+] *"` to trim the targets of spaces. – Bohemian Nov 29 '15 at 09:52

3 Answers3

4

+ is a reserved character in regular expression and split takes regExp as a parameter. You can escape it by \\+ which will now match +.

akash
  • 22,664
  • 11
  • 59
  • 87
3

Type it in square brackets

String captcha = "5 + 10";
String[] captchaSplit = captcha.split("[+]");
Ken Bekov
  • 13,696
  • 3
  • 36
  • 44
0

If you need to split String with multiple special symbols/characters, it's more convenient to use Guava library that contains Splitter class:

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