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:
- 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