python regex negative lookahead

感情迁移 提交于 2021-01-03 16:00:22

问题


when I use negative lookahead on this string

1pt 22px 3em 4px

like this

/\d+(?!px)/g

i get this result

(1, 2, 3)

and I want all of the 22px to be discarded but I don't know how should I do that


回答1:


Add a digit pattern to the lookahead:

\d+(?!\d|px)

See the regex demo

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)

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.

Both solutions will work with re.findall.



来源:https://stackoverflow.com/questions/43193485/python-regex-negative-lookahead

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!