Home > Mobile >  regex: negate a group with condition
regex: negate a group with condition

Time:11-23

is it possible to match strings if a group is not present between a starting and end position, except if the group is followed by a certain character e.g. '§'?

# match if '\.\s' is not present between 'start' and 'end'
re.search(r'start((?!\.\s).)*end', string)

for example those two strings should match:

string = 'start abc abc abc.end. '
string = 'start abc abc abc. §end '

but this string shouldn't match:

string = 'start abc abc abc. end. '

a solution would be to set a word boundary: start((?!\.\s\b).)*end but i am specifically looking to set a specific character that may be followed be the negated group

CodePudding user response:

You can add another negative lookahead after \.\s

start((?!\.\s(?!§)).)*end

See this demo at regex101

  • Related