【问题标题】:Java regex checking for special characters always returns trueJava 正则表达式检查特殊字符总是返回 true
【发布时间】:2021-03-25 19:46:36
【问题描述】:

不管我通过这个函数,一切都是真的。

asd -> should be false
asd123 -> should be false
asd 123 -> should be false
asd_123 -> should be false
asd-123 -> should be false
asd asd -> should be false

任何其他特殊字符都应该返回 true。

public static boolean checkSpecialChars(String word) {
    Pattern pattern = Pattern.compile("[a-zA-Z0-9 -_]+", Pattern.MULTILINE);
    Matcher matcher;
    matcher = pattern.matcher(word);
    boolean checker = matcher.find();

    if (checker) { return true; }
    return false;
}

我错过了什么?

【问题讨论】:

  • 试试Pattern.compile("^[a-zA-Z0-9 -_]+", Pattern.MULTILINE);
  • 您的问题根本不清楚,例如asd 没有特殊字符;那它为什么要返回false?你的意思是,它应该为a, s, d, 1, 2, 3, -, and _以外的任何字符返回true
  • 另外:find() 查找子序列。如果要匹配整个输入,请使用matches()
  • @ArvindKumarAvinash 这些都是例子。我只想包括'a-zA-Z0-9 -_',无论我尝试什么,它都是真的。表示有特殊字符。
  • @letsCode - 在这种情况下,您应该用一条语句替换整个函数体,return !Pattern.compile("[a-zA-Z0-9_-]+", Pattern.MULTILINE).matcher(word).matches();

标签: java android regex


【解决方案1】:

这里有一些问题:

  • 字符类中的- 创建了一个范围 字符,因此 -_ 无意中包含了空格和_ 之间的每个ASCII 字符,其中包括键盘上的大多数“特殊字符”(不是全部,尽管)。您需要使用反斜杠对其进行转义(\\,因为反斜杠本身也需要在 Java 中进行转义)。
  • Matcher.find() 检查是否有任何子字符串匹配,而不是整个字符串。你想要Matcher.matches()
  • 您的条件被颠倒了。如果您希望它在有 个特殊字符的情况下返回 true,它应该反转您的检查。

any 字符串与当前代码匹配并不完全正确——例如,{} 不匹配——但它肯定比预期的更广泛。

固定代码:

  public static boolean checkSpecialChars(String word) {
    Pattern pattern = Pattern.compile("[a-zA-Z0-9 \\-_]+", Pattern.MULTILINE);
    Matcher matcher;
    matcher = pattern.matcher(word);
    boolean checker = matcher.matches();

    return !checker;
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 2011-12-10
    • 2012-05-18
    • 1970-01-01
    • 2011-01-17
    相关资源
    最近更新 更多