String test1 = "This is my test string";
I want to match a string which does not contain "test"
I can do it with
Pattern p = Pattern.compile(".*?^(test).*?")
and it works but at most of sites like Regular Expressions and negating a whole character group
^(?!.*test).*$
is suggested which did not work for me.
As per my understanding ^(test)
is sufficient so why ^(?!.*test).*$
is required?
You want the following instead.
^(?:(?!test).)*$
Regular expression:
^ the beginning of the string
(?: group, but do not capture (0 or more times)
(?! look ahead to see if there is not:
test 'test'
) end of look-ahead
. any character except \n
)* end of grouping
$ before an optional \n, and the end of the string
With using ^(test)
, it is only looking for test at the beginning of the string, not negating it.
The negation ^
operator will only work inside of a character class [^ ]
, but whole words do not work inside of a character class. For example [^test]
matches any character except: (t
, e
, s
, t
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With