【问题标题】:use split() to split string like "004*034556"使用 split() 分割字符串,如 "004*034556"
【发布时间】:2013-10-27 16:51:18
【问题描述】:

在我的项目中,我使用代码来拆分字符串,例如“004*034556”,代码如下:

String string = "004*034556";
String[] parts = string.split("*");

但它出现了一些错误并强制关闭! 最后我发现如果使用“#”或其他东西它会起作用。

String string = "004#034556";
String[] parts = string.split("#");

我该如何解释?!

【问题讨论】:

  • 查看split() 的文档。 (并阅读错误)
  • 错误信息是什么?

标签: java android eclipse string split


【解决方案1】:

你忘记了一些非常琐碎的事情。

String string = "004*034556";
String[] parts = string.split("\\*");

我建议您查看Escape Characters

【讨论】:

    【解决方案2】:

    使用Pattern.quote* 视为字符串* 而不是正则表达式*(具有special meaning):

    String[] parts = string.split(Pattern.quote("*"));
    

    String#split:

    public String[] split(String regex)
                                 ↑
    

    【讨论】:

      【解决方案3】:

      参考JavaDoc

       String[] split(String regex) 
      
       Splits this string around matches of the given regular expression.
      

      当我们谈论Regex in Java时,符号“*”具有不同的含义

      因此您必须使用转义字符

      String[] parts = string.split("\\*");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-14
        • 2011-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多