-2

I have 2 strings and I want to find all locations of one string within another. String.find works but not regex.

sub: (dont want to) call in

str1: i cant (dont want to) call in

 str1.find(sub) returns 7 but 
   [(m.start(0), m.end(0)) for m in re.finditer(sub,str1)] returns empty list
cs95
  • 330,695
  • 80
  • 606
  • 657
AMisra
  • 1,769
  • 2
  • 20
  • 42

1 Answers1

1

The brackets are metacharacters in regex (used to capture groups), so you'll need to escape them if they are to be treated literally:

sub = '\(dont want to\) call in'

Alternatively, you may use re.escape, which automatically escapes the metacharacters for you:

re.finditer(re.escape('(dont want to) call in'), str1)
cs95
  • 330,695
  • 80
  • 606
  • 657