What’s the notation for any number in re? Like if I’m searching a string for any number, positive or negative. I’ve been using d+ but that can’t find 0 or -1
Advertisement
Answer
Searching for positive, negative, and/or decimals, you could use [+-]?d+(?:.d+)?
JavaScript
x
12
12
1
>>> nums = re.compile(r"[+-]?d+(?:.d+)?")
2
>>> nums.search("0.123").group(0)
3
'0.123'
4
>>> nums.search("+0.123").group(0)
5
'+0.123'
6
>>> nums.search("123").group(0)
7
'123'
8
>>> nums.search("-123").group(0)
9
'-123'
10
>>> nums.search("1").group(0)
11
'1'
12
This isn’t very smart about leading/trailing zeros, of course:
JavaScript
1
3
1
>>> nums.search("0001.20000").group(0)
2
'0001.20000'
3
Edit: Corrected the above regex to find single-digit numbers.
If you wanted to add support for exponential form, try [+-]?d+(?:.d+)?(?:[eE][+-]?d+)?
:
JavaScript
1
8
1
>>> nums2 = re.compile(r"[+-]?d+(?:.d+)?(?:[eE][+-]?d+)?")
2
>>> nums2.search("-1.23E+45").group(0)
3
'-1.23E+45'
4
>>> nums2.search("0.1e-456").group(0)
5
'0.1e-456'
6
>>> nums2.search("1e99").group(0)
7
'1e99'
8