2

I know p=re.compile('aaa|bbb') can work, but I want to rewrite p = re.compile('aaa|bbb') using variables, something like

A = 'aaa'
B = 'bbb'
p = re.compile(A|B)

but this doesn't work. How can I rewrite this so that variables are used (and it works)?

YakovL
  • 7,557
  • 12
  • 62
  • 102
程柏勳
  • 21
  • 3

1 Answers1

5

p=re.compile(A|B)

You are not doing the string concatenation correctly. What you are doing is applying the "bitwise or" (the pipe) operator to strings, which, of course, fails:

>>> 'aaa' | 'bbb'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'str' and 'str'

Instead, you can use str.join():

p = re.compile(r"|".join([A, B])) 

Demo:

>>> A = 'aaa'
>>> B = 'bbb' 
>>> r"|".join([A, B])
'aaa|bbb'

And, make sure you trust the source of A and B (beware of Regex injection attacks), or/and properly escape them.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Python already provides a function to escape them, namely, [`re.escape`](https://docs.python.org/3/library/re.html#re.escape). So to make an alternation of an arbitrary set of literal strings, you'd just do: `r'|'.join(map(re.escape, literals_to_alternate_on))`. – ShadowRanger Jul 01 '16 at 01:29