I need to write a regex that checks if:
- string starts and end with letter
- contains only letters, numbers, _ and ,
- _ can be present only between 2 letters, 2 numbers or a letter and a number
- , can be present only between 2 letters
What i have until now is this: ^[a-zA-Z][(a-zA-Z0-9_)(,a-zA-Z0-9_)]*[a-zA-Z]$
, but I don’t know how to add the last 2 requirements to it.
Can someone help?
Advertisement
Answer
Using a case insensitive match, you could use
^[a-z][a-z0-9]*(?:_[a-z0-9]+)*(?:(?<![0-9]),[a-z][a-z0-9]*(?:_[a-z0-9]+)*)*$(?<![0-9])
^
Start of string[a-z][a-z0-9]*
Match a single a-z and optional a-z0-9(?:_[a-z0-9]+)*
Optionally repeat_
and a-z0-9(?:
Non capture group(?<![0-9]),[a-z][a-z0-9]*(?:_[a-z0-9]+)*
Repeat the previous pattern asserting not 0-9 before the comma
)*
Close group and optionally repeat$(?<![0-9])
End of string, assert not ending on a digit