正则表达式否定了整个词? [英] Regex to negate the whole word?

查看:137
本文介绍了正则表达式否定了整个词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  String test1 = "This is my test string";

我想匹配一个不包含test的字符串

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

我可以用

 Pattern p = Pattern.compile(".*?^(test).*?")

它可以工作,但在大多数网站,如正则表达式和否定整个角色组
建议使用^(?!。* 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).)*$

正则表达式:

^               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

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

With using ^(test), it is only looking for test at the beginning of the string, not negating it.

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

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)

这篇关于正则表达式否定了整个词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆