gembird
gembird

Reputation: 14053

Regex doesn't validate for just one single character

This regex:

^[\w\-]+([\.\w\s\-]+)*[^\s\.]$

...works fine validating strings like this:

aaa.bbb.ccc
a . b . d
a_b.c
a-b.c d.e

The string should start with one or more characters \w or minus and can contain 0-n dots, \w or spaces. At the end there should not be any space nor dot.

The only problem is it doesn't recognize just one single characters as valid. However two characters e.g. aa, a a, --, a_` are recognized.

Q: how to change the regex to recognize one letter as valid?

Upvotes: 2

Views: 301

Answers (2)

Sivaprakash
Sivaprakash

Reputation: 305

To change the regex to recognize one letter as valid, add a * at the end like the example given below.

^[\w\-]+([\.\w\s\-]+)*[^\s\.]*$

The [^\s\.], the last part is not having any + or *, your regex needs atleast 2 character to match.

If you add * to it, it will match a character.

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627507

You can use lookarounds to impose those restrictions:

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

See the regex demo

Since the lookaheads (?!.*[\s.]$) and (?=[\w-]) do not consume characters, the [.\w\s-]+ subpattern will be able to match just 1 character strings.

The (?!.*[\s.]$) checks if the string (without newline symbol, otherwise, replace . with [\s\S]) ends DOES NOT end with a whitespace or ..

The (?=[\w-]) after ^ checks (once, at the beginning of the string) if a string starts with - or a word character.

Upvotes: 2

Related Questions