shubham deodia
shubham deodia

Reputation: 189

RegEx pattern to not allow special character except underscore

I have a special requirement, where i need the achieve the following

  1. No Special Character is allowed except _ in between string.
  2. string should not start or end with _, . and numeric value.
  3. underscore should not be allowed before or after any numeric value.

I am able to achieve most of it, but my RegEx pattern is also allowing other special characters.

How can i modify the below RegEx pattern to not allow any special character apart from underscore that to in between strings.

^[^0-9._]*[a-zA-Z0-9_]*[^0-9._]$

Upvotes: 7

Views: 35133

Answers (3)

GavinBelson
GavinBelson

Reputation: 2784

Keep it simple. Only allow underscore and alphanumeric regex:

/^[a-zA-Z0-9_]+$/

Javascript es6 implementation (works for React):

const re = /^[a-zA-Z0-9_]+$/;
re.test(variable_to_test);

Upvotes: 8

The fourth bird
The fourth bird

Reputation: 163362

What you might do is use negative lookaheads to assert your requirements:

^(?![0-9._])(?!.*[0-9._]$)(?!.*\d_)(?!.*_\d)[a-zA-Z0-9_]+$

Explanation

  • ^ Assert the start of the string
  • (?![0-9._]) Negative lookahead to assert that the string does not start with [0-9._]
  • (?!.*[0-9._]$) Negative lookahead to assert that the string does not end with [0-9._]
  • (?!.*\d_) Negative lookahead to assert that the string does not contain a digit followed by an underscore
  • (?!.*_\d) Negative lookahead to assert that the string does not contain an underscore followed by a digit
  • [a-zA-Z0-9_]+ Match what is specified in the character class one or more times. You can add to the character class what you would allow to match, for example also add a .
  • $ Assert the end of the string

Regex demo

Upvotes: 6

epascarello
epascarello

Reputation: 207511

Your opening and closing sections; [^0-9._], say match ANY character other than those.

So you need to change it to be what you can match.

/^[A-Z][A-Z0-9_]*[A-Z]$/i

And since you now said one character is valid:

/^[A-Z]([A-Z0-9_]*[A-Z])?$/i

Upvotes: 2

Related Questions