【问题标题】:Pattern not allowing words including numbers?模式不允许包含数字的单词?
【发布时间】:2019-05-13 15:29:02
【问题描述】:

我写了一个让我添加类别的程序,因为它在第一个位置有一些特殊字符和数字的问题,我做了一个正则表达式过滤器,它应该只处理特殊字符。但是,如果我现在使用包含数字的单词,该方法也会由于某种原因返回 true。

private boolean containsSpecChar () {
  Pattern pattern = Pattern.compile("[a-zA-Z0-9]");
  Pattern p = Pattern.compile("[0-9a-zA-Z]");
  String a = null;
  a = txtInKategorieName.getText();
  Matcher match= pattern.matcher(a);
  Matcher m = p.matcher(a);
  if (
  match.matches() || m.matches()
  )
  {
    return false;
  }
  else
  {
    return true;
  }
}

我也希望能够使用包含数字的单词。 谢谢

【问题讨论】:

  • 你想在什么条件下准确返回true
  • [0-9a-zA-Z][a-zA-Z0-9] 实际上是相同的,即它们匹配相同的字符。
  • 你为什么不对任何不是字母或数字的东西做find
  • 另请注意,Matcher.matches() 会尝试匹配 整个 输入,因此任何长度不是 1 的字符串都将匹配。您的检查“containsSpecChar”似乎被定义为“如果有一个不是 a-z、A-Z 或 0-9 的字符” - 所以要么使用 return a.matches(".*[^a-zA-Z0-9].*")return !a.matches("[a-zA-Z0-9]+") 或使用 Matcher.find() 以及表达式 [^a-zA-Z0-9] (如果 find() 返回 true,则字符串至少包含一个非 ascii 字母或数字的字符。

标签: java regex pattern-matching


【解决方案1】:

[a-zA-Z0-9][0-9a-zA-Z] 是一回事。

[xxx] 正则表达式模式是一个character class,它匹配一个单个字符。如果你想匹配一个或多个这些字符,你需要在末尾添加一个+quantifier

"[a-zA-Z0-9]+"

【讨论】:

    【解决方案2】:

    如果您只希望包含字母和/或数字的单词为 true,请使用 [a-zA-Z0-9]+ 作为模式。

    【讨论】:

      【解决方案3】:

      这里是.matches方式:

      public static boolean containsSpecChar () {
        Pattern pattern = Pattern.compile("[a-zA-Z0-9]+");
        String a = txtInKategorieName.getText();
        Matcher match = pattern.matcher(a);
      
        return !match.matches();
      }
      

      这里是.find 方式:

      public static boolean containsSpecChar () {
        Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
        String a = txtInKategorieName.getText();
        Matcher match = pattern.matcher(a);
      
        return match.find();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多