alxbxbx
alxbxbx

Reputation: 323

Allow one occurrence in regular expression

I would like to restrict my regex with some characters like < > @ # and allow only one occurrence of | character. So far I didn't have success.

^([^<>@#]+[|]?)$

Can't figure it out how to restrict my regex to only one occurrence of | char.

Upvotes: 6

Views: 21113

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

Use a negative lookahead:

^(?!(?:[^|]*\|){2})[^<>@#]+$

See the regex demo

Details:

  • ^ - start of a string
  • (?!(?:[^|]*\|){2}) - there cannot be 2 occurrences of 0+ chars other than | and then |
  • [^<>@#]+ - 1 or more chars other than <, >, @, #
  • $ - end of string.

Upvotes: 5

Related Questions