Regex not match with logical OR

Viewed 37

Need to match words that doesn't start with tss- or equal to tss. Tried multiple combinations but no positive results.

^(((?!(tss)).*)|(?!tss-).+)
2 Answers

To apply two negative lookahead checks against the input string, you need to simply chain them after the ^ anchor:

^(?!tss$)(?!tss-).*

The logical relationship is AND in this case:

  • ^ - start of string
  • (?!tss$) - the string must not be equal to tss
  • AND
  • (?!tss-) - the string must not start with tss-
  • .* - match the rest.

If the words can also occur in a sentence, you might also use lookarounds to assert not tss followed by either a whitespace bounadry or - using a negative lookahead.

(?<!\S)(?!tss(?:(?!\S)|-))\S+
  • (?<!\S) Assert a whitespace boundary to the left
  • (?! Negative lookahead, assert to the right is not
    • tss Match literally
    • (?:(?!\S)|-) Match either a whitespace boundary or -
  • ) Close Lookahead
  • \S+ Match 1+ non whitespace chars

Regex demo

Related