I have a special requirement, where i need the achieve the following
_ in between string._, . and 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._]$
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);
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 stringRegex demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With