validate comma separated list using regex

前端 未结 4 942
囚心锁ツ
囚心锁ツ 2021-01-17 01:23

I want to validate that the user has entered a comma separated list of words only using regex, will this work/is there a better way:

 $match = \"#^([^0-9 A-z         


        
4条回答
  •  离开以前
    2021-01-17 02:11

    I think this is what you're looking for:

    '#\G(?:[A-Za-z]+(?:\s*,\s*|$))+$#'
    

    \G anchors the match either to the beginning of the string or the position where the previous match ended. That ensures that the regex doesn't skip over any invalid characters as it tries to match each word. For example, given this string:

    'foo,&&bar'
    

    It will report failure because it can't start the second match immediately after the comma.

    Also, notice the character class: [A-Za-z]. You used [A-z] in your regex and [a-Z] in a comment, both of which are invalid (for this purpose, anyway). They may have been mere typos, but watch out for them nonetheless. Those typos could could end up causing subtle and/or serious bugs.

    EDIT: \G isn't universally supported, so check before using it in any another regex flavors.

提交回复
热议问题