Home > Mobile >  Exclude constant substring while searching for different substring remaining original indexing
Exclude constant substring while searching for different substring remaining original indexing

Time:05-18

I'd like to find (original) index of substring e.g. "cac" while ignoring some other (constant) substring e.g. "<ee>".

import re

string = "aaac<ee>acbbb"
pattern=re.compile("<ee>") # pattern to exclude
re.search("cac", pattern.sub("",string))

I've tried using regex, but this gives me only the index of newly established string (pattern excluding):

<re.Match object; span=(3, 6), match='cac'> 

Is there any way to get first and last index of "cac" regardless to inserted charcters/strings etc.?

CodePudding user response:

You can include the part to "ignore" in your pattern:

re.search("c(<ee>)*a(<ee>)*c",string)

which, for your string, produces

<re.Match object; span=(3, 10), match='c<ee>ac'>
  • Related