0

Not sure why this is not matching and not working? It appears something is wrong with the regex such that it doesn't match even though i tested it out in the online regex tester

current_name = "bob[0]"
regex_match = re.compile('%s'%current_name)
if re.match(regex_match, current_name):
    print "matched"
KAM
  • 115
  • 1
  • 3
  • 5
  • 1
    What are you trying to match from that string? The value between `[` and `]`? – Cory Kramer Jul 18 '17 at 21:48
  • 2
    You're trying to match the string `bob[0]` with the pattern `bob[0]\[[.*]]` to ? – janos Jul 18 '17 at 21:50
  • If you want to put backslashes in a regex pattern without having to double them, make it a raw string - `r'whatever'`. As it is, your backslash is getting lost, because the following character isn't part of a backslash escape. – jasonharper Jul 18 '17 at 21:53
  • i am trying to do an exact match of the string. I edited the code but still doesn't work – KAM Jul 18 '17 at 21:54
  • @KAM - then why use regex at all? `if current_name == "bob[0]": ...` will give you an exact match. – zwer Jul 18 '17 at 21:56
  • I think the square brackets are causing your problems... – jacoblaw Jul 18 '17 at 21:59

1 Answers1

0
current_name = "bob[0]"
regex_match = re.compile('%s'%current_name.replace('[', r'\['))
if re.match(regex_match, current_name):
    print "matched"

That opening square bracket was causing issues. this will print "matched"

jacoblaw
  • 1,263
  • 9
  • 9