Paul Hiles
Paul Hiles

Reputation: 9778

Regex to check for duplicate space characters

I have a requirement to write a regex to validate a text entry. The text must be between 5 and 16 characters (a-Z plus hyphen, underscore and space). This is fine but it must also check that there are not any consecutive spaces.

e.g.

hello        // PASS
hello there  // PASS
hi there you // PASS
hello  there // FAIL - two spaces between hello and there

Upvotes: 1

Views: 621

Answers (3)

Kirill
Kirill

Reputation: 406

Regex:

^([\w-_]+([\s]{0,1})[\w-_]+)$

Matches these

hello
hello there
hi there
he-llo
he_las test

And not these

hello  there
hello     there

Upvotes: 0

RokL
RokL

Reputation: 2812

In Java I would go with

"  |[^\\p{L}_ -]"

(" isn't part of the regex). If the string matches this regex then it fails. I would check the size separately in an if sentence (faster that way).

If you want to do it in some language without Unicode properties:

\s\s|[^A-Za-z_ -]

Upvotes: 1

Qtax
Qtax

Reputation: 33918

You can use something like:

/^(?!.*  )[-a-z_ ]{5,16}\z/i

Upvotes: 4

Related Questions