Skip to content
Advertisement

Regex to find strings that start and end with letter

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

Regex demo

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement