regexregex-negation

Match a string at an offset only if it's not already present in the text


I'm struggling to come up with a regex that can match a string at a specific offset, but not if that string is already present before that offset. In the following string,

PLUS This is a AC and this is an SC too

I want the regular expression

(?<=PLUS.{29})SC{1}

to find the SC at position 29 after the PLUS. And it works.

However, it also matches the text which has SC at position 11 in addition to the one at 29

PLUS This is a SC and this is an SC too

What is the regex I can use to get the match on the first text, but not on the second text?


Solution

  • You may use this regex so that SC is not matched before position 29 after matching PLUS:

    (?<=PLUS(?:(?!SC).){29})SC
    

    RegEx Demo

    RegEx Details: