仅当缺少给定的子字符串/后缀时,正则表达式才匹配整个字符串 [英] Regex to match a whole string only if it lacks a given substring/suffix

查看:41
本文介绍了仅当缺少给定的子字符串/后缀时,正则表达式才匹配整个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索过这样的问题,但是我发现的所有案例都以特定于问题的方式解决,例如在 vi 中使用 !g 来否定正则表达式匹配,或匹配其他内容, 没有正则表达式否定.

I've searched for questions like this, but all the cases I found were solved in a problem-specific manner, like using !g in vi to negate the regex matches, or matching other things, without a regex negation.

因此,我对解决此问题的纯粹"解决方案很感兴趣:

Thus, I'm interested in a "pure" solution to this:

有一组字符串,我需要用正则表达式匹配器过滤它们,以便它只留下(匹配)缺少给定子字符串的字符串.例如,过滤掉Foo":

Having a set of strings I need to filter them with a regular expression matcher so that it only leaves (matches) the strings lacking a given substring. For example, filtering out "Foo" in:

Boo
Foo
Bar
FooBar
BooFooBar
Baz

会导致:

Boo
Bar
Baz

我尝试用否定的前瞻/后视(?!regex)/(?<!regex) 来构建它,但无法弄清楚.这可能吗?

I tried constructing it with negative look aheads/behinds (?!regex)/(?<!regex), but couldn't figure it out. Is that even possible?

推荐答案

试试这个正则表达式:

^(?:(?!Foo).)*$

这将一次消耗一个字符并测试前面是否没有 Foo.同样的事情也可以用否定的后视来完成:

This will consume one character at a time and test if there is no Foo ahead. The same can be done with a negative look-behind:

^(?:.(?<!Foo))*$

但是你也可以在没有环视断言的情况下做同样的事情:

But you can also do the same without look-around assertions:

^(?:[^F]*|F(?:$|[^o].|o(?:$|[^o])))*$

这匹配除 FF 之外的任何字符,该字符要么后面没有 o,要么后面跟着一个 o 后面没有另一个 o.

This matches any character except F or an F that is either not followed by a o or if followed by an o not followed by another o.

这篇关于仅当缺少给定的子字符串/后缀时,正则表达式才匹配整个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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