Ciel
Ciel

Reputation: 17772

Regex - Prevent Double Spaces

I have a large regular expression for a name field that looks like this.

^(?:(?!(?:.*[ ]){2})(?!(?:.*[']){2})(?!(?:.*[-]){2})(?:[a-zA-Z0-9 \p{L}'-]{3,48}$))$

I am not a Regular Expression expert, I got it this far through the help of Stackoverflow and RegexBuddy. But there is one line I am having some trouble with. The first positive lookahead, (?!(?:.*[ ]){2}), this prevents there from being multiple spaces.

That is not quite what I want. I just want to make sure that there cannot be multiple spaces in sequence. Like double spaces and the like. This regex prevents there from being more than 1 space in the entire string.

I've been trying to figure out how to change that, but I am really stumped. Is there any way to enforce such a concept with the rest of the regex?

C# is where this will be executed.

Upvotes: 4

Views: 5207

Answers (2)

Lasitha Lakmal
Lasitha Lakmal

Reputation: 880

I wrote this pattern and It's working for me.

^(?!.*[\s][\s].*).+$

Upvotes: 0

Bart Kiers
Bart Kiers

Reputation: 170288

Replace (?!(?:.*[ ]){2}) with (?!.*[ ]{2})

An explanation:

(?:.*[ ]){2} first matches a single space preceded by zero or more other chars ((?:.*[ ])), which is then repeated two times ({2}).

.*[ ]{2} matches two successive spaces preceded by zero or more other chars.

Upvotes: 5

Related Questions