简体   繁体   中英

Splitting String by Regex

I've got this string here: M412 Rex | -HEADSHOT- 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?

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

User \\\\| instead of |

Change

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

to

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

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.

你需要逃避|,我的意思是..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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