Regular expression to find any number in a string

What are the notation for any number in re? For example, if I look for a string for any number, positive or negative. I used \ d + but cannot find 0 or -1

+6
source share
5 answers

Searching for positive, negative and / or decimal places, can you use [+-]?\d+(?:\.\d+)?

 >>> nums = re.compile(r"[+-]?\d+(?:\.\d+)?") >>> nums.search("0.123").group(0) '0.123' >>> nums.search("+0.123").group(0) '+0.123' >>> nums.search("123").group(0) '123' >>> nums.search("-123").group(0) '-123' >>> nums.search("1").group(0) '1' 

This is not very smart about leading / trailing zeros, of course:

 >>> nums.search("0001.20000").group(0) '0001.20000' 

Change Fixed above regex to find single bit numbers.

If you want to add exponential support, try [+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)? :

 >>> nums2 = re.compile(r"[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?") >>> nums2.search("-1.23E+45").group(0) '-1.23E+45' >>> nums2.search("0.1e-456").group(0) '0.1e-456' >>> nums2.search("1e99").group(0) '1e99' 
+17
source

\d should be fine to match any non-negative integer. \d equivalent to [0-9] (any single-digit character), therefore, of course, it will not match negative numbers. Add an additional negative sign in this case:

 \-?\d+ 

\d will definitely match 0 .

+3
source

\ d will match 0 by default, so you just need to change your regular expression so that it matches negative values, for this you can simply use:

 import re re.findall(r'[+-]?\d+', ' 1 sd 2 s 3 sfs 0 -1') 

OR

 import re re.findall(r'(?<!\S)[+-]?\d+(?!\S)', '234 +1 -10 23jjj ssf54 sdg5dfgdf') >>> ['234', '+1', '-10'] 
0
source

To match positive or negative numbers, as in -3 or +5 , use [+-]?\d+ :

 re.findall('[+-]?\d+', 'sfkdjfsdfj-1skjfslkdjf+4') # ['-1', '+4'] 

Make sure you put the negative sign last so that the compiler understands that you do not mean anything else.

0
source

According to python re documentation , \ d matches any digit if UNICODE flag is not set. If the flag is set, then it compares everything that is considered a digit in this language.

It will not correspond to negative numbers without any additions, although:

 -?\d+ 

This works, but does not get any number, since numbers are quite complex little things. Try the following:

 [-+]?\d*\.?\d+([eE][-+]?\d+)? 
0
source

Source: https://habr.com/ru/post/891565/


All Articles