Jiwon Jessica Kim
Jiwon Jessica Kim

Reputation: 103

regular expression for full name

I want my regex expression to encompass all types of full names. ex: John F. Kennedy, J.F. Kennedy, John Kennedy, etc.

([A-Z][a-zA-Z]+)[ ]*(?:\s[^\s]+)?\s([A-Z][a-zA-Z]+)

I wrote this initially, but i noticed that J.F. Kennedy would not be included. I want all types of names to be found. Would appreciate it if someone could help me solve this, thank you!
Also, is there a difference between [ ]* and \s?

Upvotes: 0

Views: 493

Answers (2)

user24343
user24343

Reputation: 912

Depending on your definition of "name", the result may vary.

One possibility:

  1. We have a capital letter at the beginning
  2. It is followed by one period or any number of lower-case letters and a trailing space
  3. 1) and 2) are followed by any number of white space and repeated at least once
  4. We have one capital letter followed by one or more lower-case letters (the complete surname).

This example leads to the regex (?:[A-Z](?:\.|[a-z]+ )\s*)+[A-Z][a-z]+

If you want the surname to be abbreviated, leave the last part away. If you want to allow '`- in the names, insert them.

Upvotes: 1

Alex G
Alex G

Reputation: 1917

You can try this regex: /^([A-Z]([a-z]+|\.)\s*){2,3}$/

It specifies that each part of the name must start with an uppercase letter followed by either a dot or lowercase letters, and there can be from 2 to 3 parts in a name.

Demo: https://regex101.com/r/cfCquW/2

Upvotes: 1

Related Questions