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'
精彩评论