-2

I'm trying to write a regex represent 'recognizes words that begin and end in "t".'

I think that the below code is true.

var re = /^t+t*t$/

But it shows 'false'

e.g.

re.test('triplet')

re.test('thought')

re.test('that')

why doesn't my answer solve the above string?

and what is the proper regex?

  • 1
    `t+` means multiple literal `t` characters. Then `t*` means zero or more literal `t`'s followed by a literal `t`. So you have left no room for any other characters than at least two literal `t`s. If what inbetween these `t`s need to be letters, then try a character class of `[a-z]*` instead of `+t*`. See [this](https://regex101.com/r/Kgw3QQ/2) – JvdV Sep 10 '20 at 12:51
  • @JvdV That's a great site to learn regex. Thanks, man. God bless you. – Donghoon Park Sep 10 '20 at 13:05
  • Using code you could also check the first and the last char instead of using a regex. – The fourth bird Sep 10 '20 at 13:13

1 Answers1

1

Your regex is wrong, as pointed out in the comments.

A naive approach could be to check if the entire word starts with t, has any number of any character and then ends with t:

var re = /^t.*t$/

of course, you could also limit the "middle" character to letters:

var re = /^t[a-z]*t$/

However, neither of these approaches check for a word that is a single "t" character. If this is a valid usecase, you'll have to handle it explicitly, e.g.:

var re = /^(t[a-z]*t|t)$/
Mureinik
  • 297,002
  • 52
  • 306
  • 350