正则表达式仅在缺少给定子字符串/后缀时匹配整个字符串
我搜索过这样的问题,但是我发现的所有情况都是以特定于问题的方式解决的,例如在 vi 中使用 !g 来否定正则表达式匹配,或者匹配其他东西,而不需要正则表达式否定。
因此,我对一个“纯粹”的解决方案感兴趣:
拥有一组字符串,我需要使用正则表达式匹配器来过滤它们,以便它只留下(匹配)缺少给定的字符串子串。例如,过滤掉“Foo”:
Boo
Foo
Bar
FooBar
BooFooBar
Baz
会导致:
Boo
Bar
Baz
我尝试用负向前瞻/后瞻构造它 (?!regex)
/(?,但无法弄清楚。这可能吗?
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:
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
Would result in:
Boo
Bar
Baz
I tried constructing it with negative look aheads/behinds (?!regex)
/(?<!regex)
, but couldn't figure it out. Is that even possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试这个正则表达式:
这将一次消耗一个字符并测试前面是否没有 Foo。使用负向后查找可以完成相同的操作:
但是您也可以在不使用环视断言的情况下执行相同的操作:
这与除 F 或 F 之外的任何字符匹配要么后面没有o,要么后面有o,后面没有另一个o。
Try this regular expression:
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:
But you can also do the same without look-around assertions:
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.