I have to make a regex that covers this conditions:
The word can start with non mandatory _
Followed by [a-zA-Z]
Followed by [a-zA-Z0-9_] — 0 or more times
And it cannot end with _
I have implemented this solution:
_*[a-zA-Z][a-zA-Z0-9_]*[^_]$
This regex can detect variables like:
try_it
But it cannot detect variables like:
x, y, z
This regex will be used for lexical analysis
Acceptable:
a100__version_2
_a100__version2
x
y
z
Non acceptable:
100__version_2
a100__version2_
_100__version_2
a100--version-2
>Solution :
This one may come in handy for matching your accepted words:
^_?[a-zA-Z](?:[a-zA-Z0-9_]+[^_])?$
Regex Explanation:
^: start of string symbol_?: an optional underscore[a-zA-Z]: a letter(?:[a-zA-Z0-9_]+[^_])?: an optional set of characters that doesn’t end with an underscore$: end of string symbol
Check the demo here.