Reputation: 189
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._]$
Upvotes: 7
Views: 35133
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
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 stringUpvotes: 6
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