简体   繁体   English

正则表达式拆分字符串

[英]Splitting String by Regex

I've got this string here: M412 Rex | -HEADSHOT- 我在这里有这个字符串: M412 Rex | -HEADSHOT- 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: 您还可以使用Pattern.quote方法来转义任何特殊字符:

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

From the Java docs : 来自Java文档

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. 此方法生成一个String,该String可用于创建与字符串s匹配的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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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