【问题标题】:Matches in a string in JavaJava中的字符串匹配
【发布时间】:2015-06-11 03:49:17
【问题描述】:

我有这个代码:

String string = "40' & 40' HC";
if(string.matches("&"))
   System.out.println("Found");

但条件不成立。为什么? 帮助表示赞赏。谢谢

【问题讨论】:

标签: java string variables match


【解决方案1】:

String.matches(String) 用于正则表达式。我建议你添加一个else(和{}),我相信你想要contains 和类似的东西

if (string.contains("&")) {
    System.out.println("Found");
} else {
    System.out.println("Not found");
}

【讨论】:

    【解决方案2】:
    String string = "40' & 40' HC";
    if(string.contains("&"))
     System.out.println("Found");
    

    将 .matches 替换为 .contains,我相信您正在尝试检查字符串中的字符。

    【讨论】:

      【解决方案3】:

      它在 JAVA 中被错误命名为 .matches() 方法。它尝试并匹配所有输入。

      String.matches 返回整个字符串是否与正则表达式匹配,而不仅仅是任何子字符串。

      使用Pattern

      String string = "40' & 40' HC";
      Pattern p = Pattern.compile("&");
      Matcher m = p.matcher(string);
      if (m.find())
        System.out.println("Found");
      

      【讨论】:

        猜你喜欢
        • 2017-08-03
        • 1970-01-01
        • 2018-01-01
        • 2012-09-14
        • 2013-01-31
        • 2011-12-17
        • 2011-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多