Yashpal S
Yashpal S

Reputation: 319

RegEx for name validation in c#

Request your some help in constructing the RegEx that should follow

I have been using below RegExp

^[a-zA-Z0-9][a-zA-Z0-9.,'\-_ ]*[a-zA-Z0-9]$

And it seems to be working fine except it requires minimum of 2 chars but my requirement is that name can be of 1 char too and in that case it should not be any of the given special chars (-_',.)

Any help in this will be much appreciated, thanks in advance.

Upvotes: 0

Views: 1624

Answers (2)

The fourth bird
The fourth bird

Reputation: 163207

You can wrap the 2nd and 3rd character class in an optional non capture group

^[a-zA-Z0-9](?:[a-zA-Z0-9.,'_ -]*[a-zA-Z0-9])?$

Regex demo

Upvotes: 1

didymus
didymus

Reputation: 270

This will match all criteria:

^\w{1,2}$|^\w+(['\-_]+\w*)+\w+$

First we handle the edge cases of 1-char and 2-char strings, that can only contain alphanumerical characters (\w).

The second part matches all strings starting with an alphanumerical character, that contain at least one special character and that end with a alphanumerical character. The (['\-_]+\w*) block matches multiple not necessarily consecutive special characters in the string (e.g. a-a-a-a-a-a---aa)

Upvotes: 0

Related Questions