How to undo any regex in Java

I have a regex that I want to deny, for example.

/(.{0,4}) 

which String.matches returns next

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

Is there a way to deny (using only regx only) so that they are as follows:

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

I am looking for a general solution that will work for any regx without re-writing the entire regex.

I reviewed the following How to undo all regex? using (?! pattern), but that doesn't seem to work for me.

Next regx

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

returns the following:

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

what I do not want. Any help would be appreciated.

+7
java regex regex-negation
Dec 22 '11 at 23:12
source share
1 answer

You need to add bindings. Original regex (minus unnecessary parentheses):

 /.{0,4} 

... matches a line containing a slash followed by zero to four characters. But, since you are using the matches() method, it is automatically bound as if it really were:

 ^/.{0,4}$ 

To achieve the opposite, you cannot rely on automatic pinning; you must make at least the final binding explicit in the view. You must also β€œstuff” the regular expression with .* , Because matches() requires the regular expression to consume the entire string:

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

But I recommend you explicitly bind the entire regex like this:

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

It does no harm, and it makes your intent perfectly clear, especially for people who have learned regular expressions from other flavors such as Perl or JavaScript. Automatically pinning the matches() method is very unusual.

+22
Dec 23 2018-11-11T00:
source share



All Articles