Java 寻找假正则表达式

Java 寻找假正则表达式,java,regex,regex-negation,Java,Regex,Regex Negation,可能重复: 我正在寻找一个不匹配任何字符串的正则表达式。 例如: 假设我有以下Java代码 public boolean checkString(String lineInput, String regex) { final Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); final Matcher m = p.matcher(lineInput); return m.matches(); }

可能重复:

我正在寻找一个不匹配任何字符串的正则表达式。 例如:

假设我有以下Java代码

public boolean checkString(String lineInput, String regex)
{
    final Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    final Matcher m = p.matcher(lineInput);
    return m.matches();
}
在某些情况下,我希望所有lineInput的checkString都返回false。因为我只控制正则表达式(而不是lineInput),是否有一个值与任何字符串都不匹配


--Yonatan

\b\b
将不匹配任何字符串,因为这是一个矛盾

\b
是与单词边界匹配的零宽度锚定
\B
也是零长度,并且位于
\B
没有的位置。因此,不可能同时见证
\b
\b

如果regex风格支持lookarounds,那么还可以使用负前瞻
(?!)
。此断言将始终失败,因为始终可以匹配空字符串

作为Java
字符串
文本,上面的模式分别是
“\\b\\b”
“(?!)”

工具书类
  • ,

您也可以尝试这些不再真正使用的古老、深奥的字符(尽管技术上可以匹配):


我认为明智的做法是:

private boolean noMatch = false;

public void setNoMatch(boolean nm) { noMatch = nm; }

public boolean checkString(String lineInput, String regex)
{
    if (noMatch) return false;
    final Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    final Matcher m = p.matcher(lineInput);
    return m.matches();
}

创建一个不匹配的正则表达式听起来像是一个可怕的混乱和对正则表达式的滥用。如果您知道不存在匹配,请在代码中这样说!您的代码将通过更易于理解和运行更快来感谢您。

不会传达意图,也不会100%保证失败。
private boolean noMatch = false;

public void setNoMatch(boolean nm) { noMatch = nm; }

public boolean checkString(String lineInput, String regex)
{
    if (noMatch) return false;
    final Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    final Matcher m = p.matcher(lineInput);
    return m.matches();
}