regex setting max number of letters in first name and last name

别说谁变了你拦得住时间么 提交于 2021-02-10 15:35:54

问题


In a form I ask the user to insert his/her First name and Last name with only a space between them, and no space before and after them.

I found the following code: ^[a-zA-Z]+ [a-zA-Z]+$

But I would wish to put restrictions 15 letters max in first, and 20 letters max in last name.


回答1:


Use a limiting quantifier:

^[a-zA-Z]{1,15} [a-zA-Z]{1,20}$
         ^^^^^          ^^^^^^

The {1,15} limiting quantifier tells the engine to match 1 to 15 characters matched with the subpattern that is located immediately to the left of it.

More from the docs:

The syntax is {min,max}, where min is zero or a positive integer number indicating the minimum number of matches, and max is an integer equal to or greater than min indicating the maximum number of matches. If the comma is present but max is omitted, the maximum number of matches is infinite. So {0,1} is the same as ?, {0,} is the same as *, and {1,} is the same as +. Omitting both the comma and max tells the engine to repeat the token exactly min times.



来源:https://stackoverflow.com/questions/44173874/regex-setting-max-number-of-letters-in-first-name-and-last-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!