Python regex lookaheadAsk Question

问题:

trying to create a regex that finds some letter combinations follow by numbers. Like ABC123, however the it could be ABC 123, ABCID:123

reg = re.compile('(ABC(?:ID\:| )?\d*?)(?:$| |,|\t)',re.IGNORECASE)

This works, however it also finds ABC by itself..

Is there way only find it if followed by numbers?

Thanks in advance

回答1:


You use a *? quantifier with \d, and it matches 0 or more digits (as few as possible).

You may use

r'ABC(?:ID:| )?\d+'

or

r'[a-z]+(?:ID:| )?\d+'

See the regex demo

Details:

Note that if you plan to also match Unicode letters in Python 2.x, you need to use

re.findall(r'[^\W\d_]+(?:ID:| )?[0-9]+', s, flags=re.U|re.I)

The re.U flag will make \W and \d classes Unicode-aware.

回答2:


You can use:

r"ABC(?:ID)?[ :]?\d+"

enter image description here

Demo

标签: regex python-2.7
© 2014 TuiCode, Inc.