Python RE for finding digits with decimal point

I am trying to infer the values โ€‹โ€‹of the digits (100.00 and 200.00) using pythons regular expressions, but when I call the code it gives nothing ... I am using python version 2.7

1) My file name is "file100", from where I need to select the values.

# cat file100
Hi this doller 100.00
Hi this is doller 200.00

2) This is my python code.

# cat count100.py
#!/usr/bin/python
import re
file = open('file100', 'r')
for digit in file.readlines():
        myre=re.match('\s\d*\.\d{2}', digit)
        if myre:
           print myre.group(1)

3) While I run this code, it gives nothing, there is no error .. nothing.

# python   count100.py
+4
source share
4 answers

Use re.search instead:

import re
file = open('file.txt', 'r')
for digit in file.readlines():
    myre = re.search(r'\s\b(\d*\.\d{2})\b', digit)
    if myre:
        print myre.group(1)

results

100.00
200.00

In the documentation :

Scan on a line that searches for the first place where an expression pattern creates a match

If you decide to use a group, you also need parentheses:

(...) , ; \number, . ('') ', () : [(] [)].

re.match :

r regex :

"r" "R"; escape- .

...

'r' 'R', escape- , , C

+2

rsplit :

with open('file100', 'r') as f:
    for line in f:
        print(line.rsplit(None, 1)[1])

:

100.00
200.00

rsplit(None,1) , , :

In [1]: s = "Hi this doller 100.00"

In [2]: s.rsplit(None,1)
Out[2]: ['Hi this doller', '100.00']

In [3]: s.rsplit(None,1)[1]
Out[3]: '100.00'

In [4]: s.rsplit(None,1)[0]
Out[4]: 'Hi this doller'

search:

import re

with open('file100', 'r') as f:
    for line in f:
        m = re.search(r"\b\d+\.\d{2}\b",line)
        if m:
            print(m.group())
+1

, re.match, , , re.search, , . , :

import re

(Python , , ). VERBOSE, . r, , , Python :

regex = re.compile(r'''
  \s      # one whitespace character, though I think this is perhaps unnecessary
  \d*     # 0 or more digits
  \.      # a dot
  \d{2}   # 2 digits
  ''', re.VERBOSE) 

, 'rU', , , .

with open('file100', 'rU') as file:

readlines, . - :

    for line in file:
        myre = regex.search(line) 
        if myre:
            print(myre.group(0)) # access the first group, there are no  
                                 # capture groups in your regex

:

100.00
200.00
+1

:

:

import re

file = """
Hi this doller 100.00
Hi this is doller 200.00
"""

for digit in file.splitlines():
    myre = re.search('\s\d*\.\d{2}', digit)
    if myre:
        print(myre.group(0))
-1

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


All Articles