Search code examples
regexcapturing-group

Full match only if the capturing group encountered once


The pattern:

(test):(thestring) 

What I want is full match only if there is just one test: before

test:thestring

But in this case there wouldn't be full match:

test:test:thestring

I've tried qualificator, but it didn't work.

Need help


Solution

  • Try this pattern: ^(?!.*((?(?<=^)|(?<=:))test(?=(:|$))).*(?1)).+$.

    The main part is ((?(?<=^)|(?<=:))test(?=(:|$))), which matches test if it's preceeded by colon : or is at the beginning of a line and it's followed by colon : or end of the line.

    (?(?<=^)|(?<=:)) this is workaround to (?<=(:|^)), but lookbehinds must have fixed length.

    Then we have backreference to first capturing group (?1), to see if there are any other test.

    This whole pattern is placed in negative lookahead (?!...), to match everything if it doesn't match pattern explained above (test matched more than one time).

    Demo