正则表达式匹配字符串包含Word而不是Word本身(Regex Match String Containing Word but not Word on its own)

我试图创建一个匹配任何字符串的正则表达式,包括那些包含"hello"但不包含"hello"字符串。

例如:

"hello1" - matches "say hello" - matches "hello there" - matches "goodbye" - matches "hello" - doesn't match

以下表达式将匹配不包含"hello"所有内容,但我无法提出符合要求的表达式。

^((?!hello).)*$

不幸的是,他们无法与此相关的额外逻辑。 我正在寻找与上述字符串匹配的单个表达式。

谢谢!

I am trying to create a regex that will match any string including those containing "hello", but not "hello" on it's own.

For example:

"hello1" - matches "say hello" - matches "hello there" - matches "goodbye" - matches "hello" - doesn't match

The following expression will match everything not containing "hello", but I can't come up with an expression fitting the requirements.

^((?!hello).)*$

Unfortunately their cannot be extra logic associated with this. I am looking for a single expression that matches the above strings.

Thanks!

最满意答案

^(?:((?!hello).)*|.+hello.*|.*hello.+)$

采用您的原始正则表达式并添加备选项( | )以:

.+hello.* - 在hello发生之前至少有一个字符 .*hello.+ - 在hello发生后至少有一个字符


另一种解决方案是只检查前瞻本身中字符串结尾的存在情况:

^(?!hello$).*$ ^(?:((?!hello).)*|.+hello.*|.*hello.+)$

Took your original regex and added alternatives (|) to either:

.+hello.* - have at least one character before the occurrence of hello .*hello.+ - have at least one character after the occurrence of hello


Another solution is to just check the presence of the end of the string in the lookahead itself:

^(?!hello$).*$

更多推荐