当负面环视不起作用时否定整个正则表达式模式 [英] negate the whole regex pattern when negative lookaround doesn't work

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

问题描述

我有一个与 P.O. 匹配的正则表达式.给定地址上的 BOX - /p\.?*o\.?*框/我.但最近我的要求更改为 NOT 匹配 P.O.盒子.换句话说,当 P.O.未找到 BOX.我试图否定该模式,以便它匹配没有 P.O.BOX 通过使用 negative lookahead,这是我目前想到的:/.*(?!p\.? *o\.? *box).*/i,但它现在不起作用:https://regex101.com/r/oN1jZ8/1

I had a regex that matches a P.O. BOX on a given address - /p\.? *o\.? *box/i. But recently my requirement changes to NOT match the P.O. BOX. In other words, the address is valid when P.O. BOX is not found. I was trying to negate that pattern so it matches an address that has no P.O. BOX by using negative lookahead, this is what I came up with so far: /.*(?!p\.? *o\.? *box).*/i, but it is not working right now: https://regex101.com/r/oN1jZ8/1

例如,我尝试匹配以下内容:

For example, I try to match the following:

  • 这是一个有效的地址

但不是以下:

  • 这是一个无效地址,因为它包含一个邮政信箱.框
  • 邮政信箱显示无效

我知道一些类似的帖子,例如:

I am aware of a few similar posts, such as:

几乎负面环视就是解决方案.

推荐答案

你应该使用这个否定前瞻:

You should use this negative lookahead:

^(?!.*p\.? *o\.? *box).*

区别在于起始锚^的使用和前瞻模式中.*的使用.

Difference is use of start anchor ^ and use of .* inside the lookahead pattern.

更新的正则表达式演示

这篇关于当负面环视不起作用时否定整个正则表达式模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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