String.split(“.”) is not splitting my long String

后端 未结 2 1414
感动是毒
感动是毒 2021-01-19 10:28

I\'m doing the following:

String test = \"this is a. example\";
String[] test2 = test.split(\".\");

the problem: test2 has no

相关标签:
2条回答
  • 2021-01-19 10:51

    The dot . is special regex character. It means match any. You need to escape the character, which in Java is done with \\.

    Once it is escaped, it won't be treated as special and will be matched just like any other character.

    So String[] test2 = test.split("\\."); should do the trick nicely!

    0 讨论(0)
  • 2021-01-19 11:14

    Note that public String[] split(String regex) takes a regex.

    You need to escape the special char ..

    Use String[] test2 = test.split("\\.");

    Now you're telling Java:

    "Don't take . as the special char ., take it as the regular char .".

    Note that escaping a regex is done by \, but in Java, \ is written as \\.


    As suggested in the comments by @OldCurmudgeon (+1), you can use public static String quote(String s) that "Returns a literal pattern String for the specified String":

    String[] test2 = test.split(Pattern.quote("."));

    0 讨论(0)
提交回复
热议问题