【问题标题】:How to use special characters & | and ⊕ in the Split() method?如何使用特殊字符 & |和 ⊕ 在 Split() 方法中?
【发布时间】:2015-01-04 15:22:23
【问题描述】:

我试过了

String text = "1&2⊕3|4";
String[] s = text.split("|⊕&");

什么也没发生,我也试过了

String text = "1&2⊕3|4";
String[] s = text.split("\\|\\⊕\\&");

什么也没发生。那么,我该怎么办?

【问题讨论】:

    标签: java special-characters tokenize stringtokenizer


    【解决方案1】:

    最简单的方法是通过添加括号来创建一个字符类

    String text = "1&2⊕3|4";
    String[] s = text.split("[|⊕&]");
    

    您可以在this excellent tutorial 中阅读有关字符类的更多信息。

    【讨论】:

      【解决方案2】:

      split 使用Regex

      您正在对String“|⊕&”进行拆分。您需要在Character Classsplit

      String[] s = text.split("[|⊕&]");
      

      虽然您需要在 Regex 中转义特殊字符 |&,但如果它们在字符类中,则不需要。实际上,只有右括号 ] 和反斜杠需要在字符类中进行转义(严格来说,- 需要转义,但如果它在类的开头或结尾都不需要)。

      【讨论】:

        猜你喜欢
        • 2017-03-07
        • 1970-01-01
        • 1970-01-01
        • 2020-03-22
        • 2014-06-12
        • 1970-01-01
        • 1970-01-01
        • 2015-07-20
        • 1970-01-01
        相关资源
        最近更新 更多