Java 正则表达式否定整个词?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23724661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:53:48  来源:igfitidea点击:

Regex to negate the whole word?

javaregex

提问by user3198603

  String test1 = "This is my test string";

I want to match a string which does not contain "test"

我想匹配一个不包含“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.

它可以工作,但在大多数网站(如正则表达式)和否定整个字符组^(?!.*test).*$的建议中,这对我不起作用。

As per my understanding ^(test)is sufficient so why ^(?!.*test).*$is required?

根据我的理解^(test)就足够了,为什么 ^(?!.*test).*$需要?

回答by hwnd

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 testat the beginning of the string, not negating it.

使用 using ^(test),它只在字符串的开头寻找test,而不是否定它。

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)

否定^运算符只能在字符类内部工作[^ ],但整个单词在字符类内部不起作用。例如[^test]匹配任何字符,除了: ( t, e, s, t)

回答by SocketM

.*= anything zero or more times

.*= 零次或多次

The Regex:

正则表达式:

^((?!test).)*$

I misunderstand it. Now I think it will work.

我误解了。现在我认为它会起作用。