regex for dot before optional word terminating numbers

91 Views Asked by At

A similar question has been asked here:

Regex to match word bounded instances with 'dot' inside?

but in my opinion my question was not answered.

I want to look for numbers between word boundaries consisting of digits, a dot and optional digits (in Python):

import re    
search_in = '55.1 55. 55.12'
reg_str = r'\d+\.\d*\b'
lst = re.findall(reg_str, search_in)
print(lst) # ['55.1', '55.12']
# expected: ['55.1', '55.', '55.12']

If the dot is at the end of the word, there will be no match. Nor could I find out why it is so neither found a solution for it. Could anyone help please?

2

There are 2 best solutions below

1
On

just remove \b (the word boundary) in your regex

import re
search_in = '55.1 55. 55.12'
reg_str = r'\d+\.\d*'
lst = re.findall(reg_str, search_in)
print(lst)

or you can use just split() function if you want to separate between spaces

search_in = '55.1 55. 55.12'
print(search_in.split(" "))

output
['55.1', '55.', '55.12']

2
On

The \b anchor represents word boundary meaning it would target the groups that are bounded by words instead of numbers, hence the middle number won't be captured since the next pattern is a number. The correct regex solution would be \b\d+\.\d*.