Jon
Jon

Reputation: 453

How do I include characters, but not allow repeating characters?

I don't want repeating question marks, but I want to allow multiple question marks anywhere as long as it's not repeated. I couldn't get it to work within the squared brackets.

([a-z#$@]+\?{1}[a-z#$@]+)

should?matchthisentirely?abc?abc

should??notwork

Upvotes: 2

Views: 1447

Answers (1)

anubhava
anubhava

Reputation: 785126

You can use a negative lookahead regex like this:

^(?!.*[?]{2})[a-z#$@?]+$

RegEx Demo

(?!.*[?]{2}) is negative lookahead, that will disallow multiple ? anywhere in the input.


If you also want to disallow ? at start and end then you can use this regex with 2 additional negative lookaheads

^(?![?])(?!.*[?]$)(?!.*[?]{2})[a-z#$@?]+$

RegEx Demo 2

Here:

  • (?![?]) - don't allow ? at the start
  • (?!.*[?]$) - don't allow ? at the end

Upvotes: 3

Related Questions