preg_match: number-alphabets and commas only

前端 未结 3 965
暖寄归人
暖寄归人 2020-12-30 12:19

How do I write a regular expression which matches number-alphabets and commas only?

I came out with this one below but it doesnt work - it accepts other punctuation

3条回答
  •  我在风中等你
    2020-12-30 12:56

    You want:

    /^[a-zA-Z0-9,]+$/
    

    You need the start ^ and end $ of string anchors. Without them the regex engine will look for any of those characters in the string and if it finds one, it will call it a day and say there's a match. With the anchors, it forces the engine to look at the whole string. Basically:

    • /[a-zA-Z0-9,]+/ matches if any of the characters are alphanumeric + comma.
    • /^[a-zA-Z0-9,]+$/ matches if all of the characters are alphanumeric + comma.

提交回复
热议问题