I am trying to pull the digit values (100.00 & 200.00) using pythons regular expressions , but when I invoke the code it doesn't yield anything... I am using python version 2.7
1) My file name is "file100" from where I need to opt 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 am running this code , it does not yield anything , no error .. nothing ..
# python count100.py
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
From the documentation:
Scan through string looking for the first location where the regular expression pattern produces a match
If you decided to use a group, parentheses are also needed:
(...) Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special sequence, described below. To match the literals '(' or ')', use ( or ), or enclose them inside a character class: [(] [)].
re.match is only valid:
If zero or more characters at the beginning of string match the regular expression pattern
r
to enclose regex
as raw strings:
String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences.
...
Unless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With