QuantumFool
QuantumFool

Reputation: 609

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

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!

Upvotes: 2

Views: 1827

Answers (4)

garlicDoge
garlicDoge

Reputation: 197

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[];
}

Upvotes: 0

liuhao
liuhao

Reputation: 679

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("\\+");

Upvotes: 0

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

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 "\\+".

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174736

+ 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("\\+");

Upvotes: 7

Related Questions