fake364
fake364

Reputation: 183

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

I have the following requirements for string

^\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

Upvotes: 1

Views: 31

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627100

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.

Upvotes: 1

Related Questions