开发者

name pattern regex

开发者 https://www.devze.com 2023-01-25 19:07 出处:网络
I wanted to get a regex pattern for name where i m using for validation purpose.The pattern which i m using now is having some problem.The problem is if i give a开发者_StackOverflow中文版 single name

I wanted to get a regex pattern for name where i m using for validation purpose.The pattern which i m using now is having some problem.The problem is if i give a开发者_StackOverflow中文版 single name like

jack morrison paul

its taking but if i give

jack  paul

where i am giving jack and double space and paul its not taking.jack is first name morrison is middle name and paul is last name.If i give first and last name and if i dont give middle name its taking double spaces while validating.I think some problem with my regex so please help me in solving this problem.I am new to this.

 //  regex pattern     
 ^([A-Za-z]([A-Za-z](\\s|\\.|_)*?)+[a-zA-Z]*$


Please format your question better. I had to read it multiple times to understand what you were trying to achieve.

My first stab:

^([\w]+)\s+([\s\w]+)\s+([\w]+)$

It will split first, middle, and last name.


How about this one:

^(\w+)\s+(?:(\w+)\s+){0,1}(\w+){0,1}$

I simplified the name captures a bit by just using \w, which will match more than just letters, but you can change that out for your more specific requirements.

In the middle: (?:(\w+)\s+){0,1} says we're going to look for one or more word characters, and one or more spaces, as a group between 0 and 1 times, meaning it's optional.

But I think the part that was throwing you was the use of just single \s, which means it has to be one space exactly. I used \s+ meaning at least one space, but possibly more. You can change this to be more limiting if you like, such as: \s{1,2} meaning between 1 and two spaces.

Hope that helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号