python正则表达式负前瞻 [英] python regex negative lookahead
问题描述
当我在这个字符串上使用负前瞻时
when I use negative lookahead on this string
1pt 22px 3em 4px
喜欢这个
/\d+(?!px)/g
我得到这个结果
(1, 2, 3)
我希望所有 22px 都被丢弃,但我不知道该怎么做
and I want all of the 22px to be discarded but I don't know how should I do that
推荐答案
向先行添加数字模式:
\d+(?!\d|px)
查看正则表达式演示
这样,您将不允许在已经匹配了 1 个或多个数字之后再匹配一个数字.
This way, you will not allow a digit to match after 1 or more digits are already matched.
另一种方法是使用原子组工作
Another way is to use an atomic group work around like
(?=(\d+))\1(?!px)
请参阅正则表达式演示.这里,(?=(\d+))
将一个或多个数字捕获到 Group 1 中,\1
反向引用将消耗这些数字,从而防止回溯到 \d+
模式.如果数字后跟 px
,(?!px)
将无法匹配,并且无法回溯以获取 2
.
See the regex demo. Here, (?=(\d+))
captures one or more digits into Group 1 and the \1
backreference will consume these digits, thus preventing backtracking into the \d+
pattern. The (?!px)
will fail the match if the digits are followed with px
and won't be able to backtrack to fetch 2
.
这两种解决方案都适用于 re.findall
.
Both solutions will work with re.findall
.
这篇关于python正则表达式负前瞻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!