-2

I need to match against a list of string values. I'm using '|'.join() to build a sting that is passed into re.match:

import re
line='GigabitEthernet0/1 is up, line protocol is up'
interfacenames=[
                'Loopback',
                'GigabitEthernet'
                ]
rex="r'" + '|'.join(interfacenames) + "'"
print rex
interface=re.match(rex,line)
print interface

The code result is:

r'Loopback|GigabitEthernet'
None

However if I copy past the string directly into match:

interface=re.match(r'Loopback|GigabitEthernet',line)

It works:

r'Loopback|GigabitEthernet'
<_sre.SRE_Match object at 0x7fcdaf2f4718>

I did try to replace .join with actual "Loopback|GigabitEthernet" in rex and it didn't work either. It looks like the pipe symbol is not treated as operator when passed from string. Any thoughts how to fix it?

lem
  • 9
  • 1
  • the raw prefix is useless in that case. Problem is that your generated regex has simple quotes in it. Remove them: `rex = '|'.join(interfacenames)` – Jean-François Fabre Jan 12 '17 at 20:41
  • You didn't copy/paste the same string when you did your test. It would have to be `re.match("r'Loopback|GigabitEthernet'",line)`. – melpomene Jan 12 '17 at 20:41
  • Thank you. Was sure I did try it at some point but clearly did something wrong. It works perfectly. – lem Jan 13 '17 at 00:17

2 Answers2

2

You use the r' prefix as a part of a string literal. This is how it could be used:

rex=r'|'.join(interfacenames)

See the Python demo

If the interfacenames may contain special regex metacharacters, escape the values like this:

rex=r'|'.join([re.escape(x) for x in interfacenames])

Also, if you plan to match the strings not only at the start of the string, use re.search rather than re.match. See What is the difference between Python's re.search and re.match?

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

You don't need to put "r'" at the beginning and "'". That's part of the syntax for literal raw strings, it's not part of the string itself.

rex = '|'.join(interfacenames)
Barmar
  • 741,623
  • 53
  • 500
  • 612