regex doesn't work as expected, not allowed characters at the start and one in all string

Viewed 27

I have the following requirements for string

  • not allowed + - and = at the beginning of the field
  • vertical slash | is not allowed at all for the word entry
  • ignore spaces around the entry
^\s*[^\+\-\=|][^|]*\s*$

I've written this regex, I expected that it should work, but it doesn't. I've tried " +a" and it matches,it's incorrect. Removing [^|]* or * from \s* makes my regex more valid (" +a" not matches regex - it's correct), but I need a full valid regex but not partially valid

1 Answers

The +a matched because the space at the start was matched with [^\+\-\=|]. This pattern matches any char but +, -, =, and |, and thus matches whitespace.

That means, you need another requirement: no whitespace as the first char.

You can use

^\s*[^\s+=-|][^|]*\s*$

Note there is no need to escape lots of chars in character classes, and [^\s+=-|] matches any one char but whitespace, +,=, - and |.

See the regex demo.

Related