0

This is string that I got

This given stirng

Immunodeficiency with increased immunoglobulin [M] [IgM] Maternal care for anti-D [Rh] antibodies, unspecified trimester

I tried to finding multiple occurrences of a string within a string in Python, and get their index.

so, with a input string

  char = random input string

I wanted result like this:

result = [[index, index, index],[index, index, index ]]

so, this is code that I used.

            a = [m.start() for m in re.finditer(char,given string)]

,but it didn't work for metacharacters, and caused re.error: unterminated character set at position 0

how can I improve this code?

goldenasian
  • 264
  • 1
  • 2
  • 9

1 Answers1

2

If you want to use re.finditer() with a random input string, you need to escape it in case it contains characters that have special meaning in regular expressions.

regex = re.escape(char)
a = [m.start() for m in re.finditer(regex,given string)]
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks a lot, it solved my problem, but I used re.finditer(), because that's the only think that learned. Is there any better function for finding occurrences of a string? – goldenasian Apr 09 '20 at 22:04
  • Apparently not. See https://stackoverflow.com/questions/4664850/how-to-find-all-occurrences-of-a-substring – Barmar Apr 09 '20 at 22:06