Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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._]$

like image 422
shubham deodia Avatar asked Jul 17 '26 07:07

shubham deodia


2 Answers

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);
like image 52
GavinBelson Avatar answered Jul 18 '26 21:07

GavinBelson


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

like image 40
The fourth bird Avatar answered Jul 18 '26 21:07

The fourth bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!