8
  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?

Community
  • 1
  • 1
user3198603
  • 5,528
  • 13
  • 65
  • 125

2 Answers2

28

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)

hwnd
  • 69,796
  • 4
  • 95
  • 132
  • 1
    why not just ^(test) ? – user3198603 May 18 '14 at 17:14
  • 4
    @user3198603 The `^` operator for negation only works in a character class, for example `[^t]` would accept any character that is not the letter t. But that does not work for whole words. That is, `[^test]` would accept any *letter* that is not t, e, or s. Outside of a character class, `^` is an anchor for beginning of line. – Daniël Knippers May 18 '14 at 17:19
  • `\v^(%(test)@!.)*$` for regex in vim – xialu Jun 24 '19 at 09:24
-2

.* = anything zero or more times

The Regex:

^((?!test).)*$

I misunderstand it. Now I think it will work.

SocketM
  • 564
  • 1
  • 19
  • 34