Regular Expressions Code

Hi all,
can any one help with the following code…

print(re.findall('[0-9]+.[0-9]',"my 2 fav num are 12.368  11x89"))
print(re.findall('[0-9]+\\.[0-9]+',"my 2 fav num are 12.368F7 11x89"))

print(re.findall('[0-9]+\\.[0-9]+[^A-Z][^a-z]',"my 2 fav num are 12.3F68 12.36 11x89"))

@Sandhi_Kranthi What is the problem you are facing?

second instruction extracting the number upto 12.368 as it not a number why it is extracting…

Third instruction is extracting upto 12.36 1 why i didn’t understood…can you please help me out

@Sandhi_Kranthi
Here are the following outputs:

>>> print(re.findall('[0-9]+.[0-9]',"my 2 fav num are 12.368  11x89"))
['12.3', '11x8']
>>> print(re.findall('[0-9]+\\.[0-9]+',"my 2 fav num are 12.368F7 11x89"))
['12.368']
>>> print(re.findall('[0-9]+\\.[0-9]+[^A-Z][^a-z]',"my 2 fav num are 12.3F68 12.36 11x89"))
['12.36 1']

Assuming that you know what re.findall does, the first statement has a regex pattern like this: [0-9]+.[0-9] What is essentially means is the following:

  • it will match a numeric value [0-9] (0,1,2…9)
  • If there is a match, it will try to find one or more matches of this pattern. + means one or more matches of the pattern
  • now there is a . which means it will match a single character .
  • now there is same pattern again [0-9] which matches any single digit number. But note there is not + thus, only single digit will be matched. So you get a output like 12.3

Similarly, for the second one I think you make out what is going on.

For the third example, its similar to the second pattern, but it has some extra things which the regex engine will try to match. That’s why the outputs are different for second and third. Basically, at the end of the pattern, there are these [^A-Z][^a-z]. ^ means negetaion. So whatever that doesn’t matches [A-Z] [^A-Z] will match it. Thus there is only one match 12.36 1

Hope this helps! Happy Learning! :smile: