0

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.

1
  • 1
    Can you explain what you mean? What variable would you like to use, and what would be your expected input and output? Commented Feb 20, 2013 at 5:18

3 Answers 3

1

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)))
Sign up to request clarification or add additional context in comments.

4 Comments

Would that be '\d{%i}:\d{%i}' for the integer value (even though %d works)?
Doesn't matter, %i and %d are exactly the same. I've always used and seen %d.
I'm sorry, I want to put a variable in place of (?P<hh>\d) sys.argv[1]:sys.argv[2] to find and correct the output line going to
@ParkKwansik Without changing your code too much... 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.
1

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)

Comments

0

You can pass it in as a string (I'd escape it first):

m = re.compile(re.escape(hh) + r':\d{2}')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.