开发者

Regular expression to match only two numbers

I have such string:

something: 20 kg/ something: 120 kg

I have this regex (开发者_运维问答"[0-9]{1,2} kg", string), but it returns 20kg both times. I need to return 20kg only in first case.


Try this:

(?<!\d)\d{1,2}\s+kg

The (?<!...) is a negative look behind. So it matches one or two digits not preceded by a digit. I also changed the literal space with one or more space chars.

Seeing you've asked Python questions, here's a demo in Python:

#!/usr/bin/env python
import re
string = 'something: 20 kg/ something: 120 kg'
print re.findall(r'(?<!\d)\d{1,2}\s+kg', string)

which will print ['20 kg']

edit

As @Tim mentioned, a word boundary \b is enough: r'\b\d{1,2}\s+kg'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜