【问题标题】:Removing '|' , numbers and replacing with empty character in string -Java删除“|” ,数字并用字符串中的空字符替换-Java
【发布时间】:2014-08-26 18:13:50
【问题描述】:

例子:

    String s1 = JOptionPane.showInputDialog("enter the string");
    String s2 = "h2ow |are you";
   
    
    if (s2.replace all("\\d+","").replaceAll("|", "").contains(s1))
        JOptionPane.showMessageDialog(null, "true");
    
    else
        JOptionPane.showMessageDialog(null, "false");

如果我输入输入为“如何”输出为真

但是,当我输入“how are”时,输出为假。

有没有办法替换'|'(竖线)?

【问题讨论】:

    标签: java string replace


    【解决方案1】:

    您需要转义管道字符 (|)。未转义,是regular expression "or" operator

    试试这个:

    s2.replaceAll("\\d|\\|", "").contains(s1)
    

    这使用文字管道(regex=\|,Java 转义="\\|")和实际的或管道(|)。它说,用空替换任何数字或文字管道字符。

    注意,正如@alfasin 所说,该函数被命名为replaceAll,而不是replace_all

    另外,如果这个函数要在同一次执行中重复使用,那么考虑reusing the matcher object,而不是使用字符串版本(每次都会创建一个 Matcher 对象)。


    请考虑将 Stack Overflow Regular Expression FAQ 加入书签以供将来参考。

    【讨论】:

      【解决方案2】:

      除了男生回答你也可以使用:

      if (s2.replaceAll("[\\d\\|]","").contains(s1))
      

      这个正则表达式在性能上比执行两次.replaceAll 或在正则表达式上使用| 更好(正则表达式 OR)

      【讨论】:

        【解决方案3】:

        | 表示或使用正则表达式,因此转义 | 以匹配实际字符:

        if (s2.replaceAll("\\d+","").replaceAll("\\|", "").contains(s1))
        

        【讨论】:

          猜你喜欢
          • 2013-02-25
          • 1970-01-01
          • 2017-03-24
          • 1970-01-01
          • 2011-04-29
          • 1970-01-01
          • 2013-07-09
          • 1970-01-01
          • 2013-01-04
          相关资源
          最近更新 更多