Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables in Python regular expression [duplicate]

Tags:

python

regex

I'm parsing a file and looking in the lines for username-# where the username will change and there can be any number of digits [0-9] after the dash.

I have tried nearly every combination trying to use the variable username in the regular expression.

Am I even close with something like re.compile('%s-\d*'%user)?

like image 372
utahwithak Avatar asked May 05 '11 15:05

utahwithak


2 Answers

Working as it should:

>>> user = 'heinz'
>>> import re
>>> regex = re.compile('%s-\d*'%user)
>>> regex.match('heinz-1')
<_sre.SRE_Match object at 0x2b27a18e3f38>
>>> regex.match('heinz-11')
<_sre.SRE_Match object at 0x2b27a2f7c030>
>>> regex.match('heinz-12345')
<_sre.SRE_Match object at 0x2b27a18e3f38>
>>> regex.match('foo-12345')
like image 148
Andreas Jung Avatar answered Oct 13 '22 21:10

Andreas Jung


You could create the string using .format() method of string:

re.compile('{}-\d*'.format(user))
like image 36
John Gaines Jr. Avatar answered Oct 13 '22 20:10

John Gaines Jr.