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


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

You may use

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


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

See the regex demo


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.


You can use:

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

enter image description here


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