Shona Shona - 1 year ago 148
Javascript Question

matching words starting and ending with same letter

I am trying to come up with a regex to match words starting and ending with same vowel. My question is, is this an elegant all-encompassing solution or am i missing something? So far this is what I have come up after a quick brainstroming. My preferred environment is javascript/python without special libraries etc. Thanks for helpful suggestions.

  • soln. 1) re = /(^[aeiou])\w+\1/i;

  • soln. 2) re = /(^[aeiou])[a-zA-Z]+\1/i;

  • console.log(re.test("abcda")); //true

  • console.log(re.test("abcdo")); //false

Answer Source

Words can be matched using a word boundary \b:

var re = /\b([aeiou])[a-z]+\1\b/i;

The regex demo

The regex matches:

  • \b - leading word boundary (because the pattern after it matches a word character)
  • ([aeiou]) - Group 1 capturing a vowel from the specified range
  • [a-z]+ - one or more letters (both upper- and lowercase since the /i modifier is used)
  • \1 - backreference to the vowel captured with the first group
  • \b - trailing word boundary
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download