Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need help figuring out short regex – how to match 1 a char, then either of a set including the char, then another char

My regex does not match phrases as intended, and I don’t know if it’s possible or not to do what I’m trying to.

Intended match (as string progresses)

  • phrase starts with t
  • FIRST character after beginning ‘t’ must not be ‘t’
  • has any number of ‘t’ or ‘y’ characters (can be 0)
  • must end with y

Should match:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • ty
  • tytyyy

Should not match:

  • tty
  • tyt

Regex

/t[ty]*y/

this will match ty
but it will also match tty

Other Regex

t(?!t)[ty]*y

this matches tty for some reason, even though I clearly specify there cannot be a t after the initial t, after which there can be any number of t and y, and it should end with y?

I am trying to find a middleground but no matter how I change my regex, it ends up failing at least 1 other check i mentioned in the list above.

>Solution :

^t([^t].*)?y$Regex 101

  • ^ – start of word
  • t – begins with t
  • (
    • [^t] – a non-t character
    • .* – any following characters
  • )? – above are optional (they are within the group)
  • y – ends in y
  • $ – end of word

Matches:

  • ty
  • tytyyy

Does not match:

  • tty
  • tyt
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading