Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
939 views
in Technique[技术] by (71.8m points)

python regex negative lookahead

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...