Splitting a Java String on the "+" symbol gives an error

1.8k Views Asked by At

I'm currently writing a java program, one of whose sub-tasks is to take a string and split it at a location. So, here's one little snippet of my code:

public class Driver
{
    public static void main(String[] args)
    {
        String str = "a+d";
        String[] strparts = str.split("+");
        for (String item : strparts)
        {
            System.out.println(item);
        }
    }
}

I was expecting the result:

a
d

However, to my surprise, I get:

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+
^

    at java.util.regex.Pattern.error(Pattern.java:1955)
    at java.util.regex.Pattern.sequence(Pattern.java:2123)
    at java.util.regex.Pattern.expr(Pattern.java:1996)
    at java.util.regex.Pattern.compile(Pattern.java:1696)
    at java.util.regex.Pattern.<init>(Pattern.java:1351)
    at java.util.regex.Pattern.compile(Pattern.java:1028)
    at java.lang.String.split(String.java:2367)
    at java.lang.String.split(String.java:2409)
    at Test.Driver.main(Driver.java:8)

What's going on?
Thanks!

4

There are 4 best solutions below

2
On BEST ANSWER

+ is a special metacharacter in regex which repeats the previous character one or more times. You need to escape it to match a literal +

String[] strparts = str.split("\\+");
0
On

You also could create a return type method for your String. This would make it much easier if you want to implement other String manipulating methods.

public static void main(String[] args) {
    String plainString  = toArray("a+b");
}
public static String[] toArray(String s) {
    String myArray[] = s.split("\\+");
    return myArray[];
}
0
On

The symbol + is part of regex, need to prefix with backslash,

String[] strparts = str.split("\\+");

In literal Java strings the backslash is an escape character. The literal string "\\" is a single backslash. In regular expressions, the backslash is also an escape character.

Since + is a symbol used in regular expression, as a Java string, this is written as "\\+".

0
On

As we can see from Java pai:

public String[] split(String regex)

Splits this string around matches of the given regular expression.

So,here a regular expression is needed.

    String[] strparts = str.split("\\+");