Match the same start and end character of a string with Regex

后端 未结 4 742
醉话见心
醉话见心 2021-02-05 02:02

I\'m trying to match the start and end character of a string to be the same vowel. My regex is working in most scenarios, but failing in others:

var re = /([aeio         


        
4条回答
  •  伪装坚强ぢ
    2021-02-05 02:48

    You need to add anchors to your string.

    When you have, for example:

    aeqwae
    

    You say the output is true, but it's not valid because a is not the same as e. Well, regex simply matches the previous character (before e), which is a. Thus, the match is valid. So, you get this:

    [aeqwa]e
    

    The string enclosed in the brackets is the actual match and why it returns true.

    If you change your regex to this:

    /^([aeiou]).*\1$/
    

    By adding ^, you tell it that the start of the match must be the start of the string and by adding $ you tell it that the end of the match must be the end of the string. This way, if there's a match, the whole string must be matched, meaning that aeqwae will no longer get matched.

    A great tool for testing regex is Regex101. Give it a try!

    Note: Depending on your input, you might need to set the global (g) or multi-line (m) flag. The global flag prevents regex from returning after the first match. The multi-line flag makes ^ and $ match the start and end of the line (not the string). I used both of them when testing with your input.

提交回复
热议问题