Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to negate the whole word? [duplicate]

Tags:

java

regex

  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?

like image 222
user3198603 Avatar asked May 18 '14 17:05

user3198603


1 Answers

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)

like image 115
hwnd Avatar answered Oct 06 '22 00:10

hwnd