3
votes

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

3
Also, below pattern works for me, but i know for sure it's not the best solution. ^[^0-9`|\~|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\+|\=|\[|\{|\]|\}|\||\\|\'|\<|\,|\.|\>|\?|\/|\""|\;|\:|\s]*[a-zA-Z0-9_]*[^`|\~|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\+|\=|\[|\{|\]|\}|\||\\|\'|\<|\,|\.|\>|\?|\/|\""|\;|\:|\s]*[^0-9`|\~|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\+|\=|\[|\{|\]|\}|\||\\|\'|\<|\,|\.|\>|\?|\/|\""|\;|\:|\s]$shubham deodia
Try /^(?=[A-Z])(?=.*[A-Z]$)(?!.*_\d)(?!.*\d_)\w+$/iWiktor Stribiżew

3 Answers

2
votes

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
2
votes

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);
1
votes

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