20

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)?

user
  • 4,960
  • 7
  • 46
  • 70
utahwithak
  • 6,115
  • 2
  • 39
  • 60

4 Answers4

22

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')
Andreas Jung
  • 1
  • 19
  • 73
  • 119
  • I feel really stupid now. So why is it that when I try and create it in a pdb break it gives me a syntaxerror – utahwithak May 05 '11 at 16:00
  • In the python debugger, it wouldn't let me create it as I was stepping through. Isn't the debugger a normal python interpreter? http://docs.python.org/library/pdb.html – utahwithak May 05 '11 at 16:06
  • WHat are you talking about? The code is copy-pasted from the interactive console? Are you trying to copy-pasted code in your debugger? – Andreas Jung May 05 '11 at 16:07
  • 2
    Make sure to use `re.escape()` as @Steven said in his answer. E.g. `regex = re.compile('%s-\d*'%re.escape(user))`. – jtpereyda Sep 17 '15 at 23:48
3

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

re.compile('{}-\d*'.format(user))
John Gaines Jr.
  • 10,516
  • 1
  • 24
  • 25
3

Yes, concatenate the regex yourself, or use string formatting. But don't forget to use re.escape() if your variable could contain characters that have special meaning in regular expressions.

Steven
  • 26,675
  • 5
  • 60
  • 50
0

What about:

re.compile(user + '-\d*')
hsz
  • 143,040
  • 58
  • 252
  • 308