Search code examples
c#.netregexlookbehind

Regex lookbehind assertion issue


this is my current regex:

(?<=[\$T|\s|\p{P}|\$%\$%])sampleString

I want to match all sampleString in my richtextBox

and some instance of sample string in my richtextBox is something like this :

$TsampleString
$%$%sampleString

The problem is that my regex matches this : TsampleString, $sampleString, %sampleString.

How can I fix this regex lookbehind assertion? thanks


Solution

  • You're building the regex wrong. You've got a character class (denoted by your square brackets) where you just want to list alternatives. Try:

    (?<=\$T|\s|\p{P}|\$%\$%)sampleString
    

    Edit: Wait, I just tested. Why are you using \p{P}? That's punctuation. % would be matched, among others.

    Edit II: " the only characters need to be on the left side of sampleString is $T and $%$%"

    Ok, that makes it simpler:

    (?<=\$T|\$%\$%)sampleString