0

Here is the problem. In this case how do I match string containing either "foo" or "bar".

a = 'foo'

b = 'bar'

string = 'The bar is closed'

reg = re.match(a + r"|" + b + r"(.*)", string)

  • 1
    What's wrong with `foo|bar`? – Aran-Fey May 14 '18 at 05:52
  • These are variables whose value also is dynamic. It is not sure that I always get foo or bar. I might get something else as well – Ananda R May 14 '18 at 05:55
  • 1
    So you want `\b(?:foo|bar)\b`? – Aran-Fey May 14 '18 at 05:56
  • No. There will be two variables (whose value can be anything) and I need to check the regex has any of them matching. In perl it is something like $string =~ /($variable1|$variable2)/ . This is what I'm looking for – Ananda R May 14 '18 at 06:01
  • I don't understand. You want to use the regex *on* the variables? So something like `reg_a = re.match(some_regex, a)` and `reg_b = re.match(some_regex, b)`? Please try to clarify your question and add some example in- and output. – Aran-Fey May 14 '18 at 06:03
  • Are you asking how to do string interpolation/formatiing? – juanpa.arrivillaga May 14 '18 at 06:16
  • `a + r"|" + b + r"(.*)"` would work fine. However, use `re.search` instead of `re.match`, because `re.match` *always matches from the beginning. It would be like adding an `^` anchor... – juanpa.arrivillaga May 14 '18 at 06:18
  • Hi Juanapa, Thanks a lot it worked.. Actually I tried a similar thing before. But looks like I made a mistake in there. – Ananda R May 16 '18 at 12:01

0 Answers0