Find all digits that can be followed by a decimal point

I am trying to find combinations of numbers followed by a decimal point and another number. The last ending decimal point may be missing

E.g., 
1.3.3 --> Here there are two combinations 1.3 and 3.3
1.3.3. --> Here there are two combinations 1.3 and 3.3

      

However, when I run the following code?

st='1.2.3 The Mismatch of Accommodation and Disparity and the Depths of Focus and of Field'
import re
re.findall('\d\.\d+',st)
['1.2']

      

What am I doing wrong?

+3


source to share


2 answers


You can match 1 + numbers in the consumption pattern and grab the fractional part inside the positive view, then join the groups:

import re
st='1.2.3 The Mismatch of Accommodation and Disparity and the Depths of Focus and of Field'
print(["{}{}".format(x,y) for x,y in re.findall(r'(\d+)(?=(\.\d+))',st)])

      

See a demo version of the Python and the demo version of the regex .



Regular Expression Details :

  • (\d+)

    - Group 1: one or more digits
  • (?=(\.\d+))

    - a positive view that requires:
    • (\.\d+)

      - Group 2: point and then 1 + numbers
+3


source


Since you cannot match the same characters twice, you need to put the capturing group inside the lookahead statement to avoid consuming the digits that are to the right of the dot:



re.findall(r'(?=(\d+\.\d+))\d+\.', st)

      

+3


source







All Articles