Home > Blockchain >  RegEx for name validation in c#
RegEx for name validation in c#

Time:12-09

Request your some help in constructing the RegEx that should follow

  • Should start and end with alphanumeric char
  • Should be minimum of 1 char
  • Should not start/end with given special chars (-_',.)
  • Shall contain (-_',.) in between the word

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.

CodePudding user response:

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

CodePudding user response:

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)

  • Related