简体   繁体   English

在“+”符号上拆分Java字符串会出错

[英]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. 我正在编写一个java程序,其中一个子任务是获取一个字符串并将其拆分到一个位置。 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! 谢谢!

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

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. 在文字Java字符串中,反斜杠是一个转义字符。 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 "\\\\+" . 由于+是正则表达式中使用的符号,因此将其写为"\\\\+"

As we can see from Java pai : 正如我们从Java pai中看到的那样:

public String[] split(String regex) 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("\\+");

You also could create a return type method for your String. 您还可以为String创建返回类型方法。 This would make it much easier if you want to implement other String manipulating methods. 如果要实现其他String操作方法,这将使其更容易。

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

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

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