skiwi
skiwi

Reputation: 69259

Splitting String by Regex

I've got this string here: M412 Rex | -HEADSHOT-. I want to split it on the | to get the first name, however my code is not working as intended.

        System.out.println("weaponPart = " + weaponPart);
        String[] weaponPartParts = weaponPart.split(" | ");
        for (String s : weaponPartParts) {
            System.out.println("s = " + s);
        }
        System.out.println();

Prints out:

weaponPart = M412 Rex | -HEADSHOT-
s = M412
s = Rex
s = |
s = -HEADSHOT-

I'm assuming it has something to do with the regex matching, but what is actually going on?

Upvotes: 2

Views: 92

Answers (5)

anotherdave
anotherdave

Reputation: 6744

You could also using the Pattern.quote method to escape any special characters:

String[] weaponPartParts = weaponPart.split(Pattern.quote(" | "));

From the Java docs:

This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern.

Metacharacters or escape sequences in the input sequence will be given no special meaning.

Upvotes: 2

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

You must double escape the | that is a special character in a regex: \\|. (It means "OR")

In other words, your actual pattern means "split when you find a space OR a space".

Thus the good line is:

String[] weaponPartParts = weaponPart.split(" \\| ");

As an aside comment these special characters \ | ( ) [ { ^ $ * + ? . are the "Dirty Dozen".

Upvotes: 4

Rakesh KR
Rakesh KR

Reputation: 6527

String weaponPart = "M412 Rex | -HEADSHOT-";
System.out.println("First Name::"+weaponPart.split("\\|")[0]);

Upvotes: 1

Peter_James
Peter_James

Reputation: 647

You need to escape the |, what I mean is..

String[] weaponPartParts = weaponPart.split(" \\| ");

Upvotes: 1

Mengjun
Mengjun

Reputation: 3197

User \\| instead of |

Change

String[] weaponPartParts = weaponPart.split("|");

to

String[] weaponPartParts = weaponPart.split("\\|");

Upvotes: 2

Related Questions