如何否定Java中的任何正则表达式 [英] how to negate any regular expression in Java

查看:138
本文介绍了如何否定Java中的任何正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我想要否定的正则表达式,例如

I have a regular expression which I want to negate, e.g.

/(.{0,4})

String.matches返回以下内容

which String.matches returns the following

"/1234" true
"/12" true
"/" true
"" false
"1234" false
"/12345" false

有没有办法否定(仅使用regx)上面的内容,以便结果是:

Is there a way to negate (using regx only) to the above so that the results are:

"/1234" false
"/12" false
"/" false
"" true
"1234" true
"/12345" true

我正在寻找一种适用于任何regx的通用解决方案,无需重写整个正则表达式。

I'm looking for a general solution that would work for any regx without re-writing the whole regex.

我查看了以下
<一个href =https://stackoverflow.com/questions/2637675/how-to-negate-the-whole-regex>如何否定整个正则表达式?使用(?!pattern),但是没有似乎对我有用。

I have looked at the following How to negate the whole regex? using (?! pattern), but that doesn't seem to work for me.

以下regx

(?!/(.{0,4}))

返回以下内容:

"/1234" false
"/12" false
"/" false
"" true
"1234" false
"/12345" false

这不是我想要的。
任何帮助都将不胜感激。

which is not what I want. Any help would be appreciated.

推荐答案

您需要添加锚点。原始正则表达式(减去不需要的括号):

You need to add anchors. The original regex (minus the unneeded parentheses):

/.{0,4}

...匹配包含斜杠的字符串,后跟0到4个字符。但是,因为你正在使用 matches()方法,它会自动锚定,就像它真的一样:

...matches a string that contains a slash followed by zero to four more characters. But, because you're using the matches() method it's automatically anchored, as if it were really:

^/.{0,4}$

实现相反,你不能依靠自动锚定;你必须至少在前瞻中明确表明结束锚。您还必须使用。* 填充正则表达式,因为 matches()要求正则表达式使用整个string:

To achieve the inverse of that, you can't rely on automatic anchoring; you have to make at least the end anchor explicit within the lookahead. You also have to "pad" the regex with a .* because matches() requires the regex to consume the whole string:

(?!/.{0,4}$).*

但我建议您明确锚定整个正则表达式,如下所示:

But I recommend that you explicitly anchor the whole regex, like so:

^(?!/.{0,4}$).*$

它没有任何害处,它使你的意图非常清楚,特别是对于那些从Perl或JavaScript等其他版本学习正则表达式的人。自动锚定 matches()方法非常不寻常。

It does no harm, and it makes your intention perfectly clear, especially to people who learned regexes from other flavors like Perl or JavaScript. The automatic anchoring of the matches() method is highly unusual.

这篇关于如何否定Java中的任何正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆