I would like to use a numeric variable regular expression part.
What should I do if I want to use a variable in this part (?P<hh>\d)
I want to output lines that contain the input number.
I would like to use a numeric variable regular expression part.
What should I do if I want to use a variable in this part (?P<hh>\d)
I want to output lines that contain the input number.
Using string interpolation:
m = re.compile(r'\d{%d}:\d{%d}' % (var1, var2))
If the vars aren't already integers you may need to convert types like so:
m = re.compile(r'\d{%d}:\d{%d}' % (int(var1), int(var2)))
'\d{%i}:\d{%i}' for the integer value (even though %d works)?%i and %d are exactly the same. I've always used and seen %d.LOG_FILE = '/home/text' hh = sys.argv[1] m = '%s:%s' % (hh, sys.argv[2]) f = open(LOG_FILE) lines = f.readlines(10000) for line in lines: r1 = line.find(m) if r1: print line f.close() I'm assuming you want to take sys.argv[1] and sys.argv[2] and turn them into a string separated by : then search for lines with that string and print them. There's no reason in that case to use a regular expression, so I switched to using the find string function. I removed some unnecessary code as well.Your question isn't clear.
If you want to capture some specific part of the regex, you have to create groups (using pharentesis):
hh = sys.argv[1]
m = re.compile(r'(?P<hh>\d):(\d{2})')
match = m.match(hh)
print match.group(1)
print match.group(2)
for example, if hh = '1:23', the above code will print:
1
23
Now, if what you need is replace \d{2} by some variable, you can do:
variable = r'\d{2}'
m = re.compile(r'(?P<hh>\d):%s' % variable)
or if you just want to replace the 2, you can do:
variable = '2'
m = re.compile(r'(?P<hh>\d):\d{%s}' % variable)
Another option could be using:
r'(?P<hh>\d):{0}'.format(variable)