Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to find "lastname, firstname middlename" format

Tags:

java

regex

I am trying to find the format "abc, def g" which is a name format "lastname, firstname middlename". I think the best suited method is regex but I do not have any idea in Regex. I tried doing some learning in regex and tried some expression also but no luck. One additional point there may be more than one spaces between the words.

This is what I tried. But this is not working.

(([A-Z][,]\s?)*([A-Z][a-z]+\s?)+([A-Z]\s?[a-z]*)*)

Need help ! Any idea how I can do this so that only the above expression match.

Thanks !

ANSWER

Finally I am using

([A-Za-z]+),\\s*([A-Za-z]+)\\s*([A-Za-z]+)

Thanks to everyone for the suggestions.

like image 225
A Paul Avatar asked Sep 12 '14 05:09

A Paul


People also ask

How do you match a name in regex?

p{L} => matches any kind of letter character from any language. p{N} => matches any kind of numeric character. *- => matches asterisk and hyphen. + => Quantifier — Matches between one to unlimited times (greedy)

What is the difference between () and [] in regex?

In other words, square brackets match exactly one character. (a-z0-9) will match two characters, the first is one of abcdefghijklmnopqrstuvwxyz , the second is one of 0123456789 , just as if the parenthesis weren't there. The () will allow you to read exactly which characters were matched.

How do I find a specific character in a regular expression?

There is a method for matching specific characters using regular expressions, by defining them inside square brackets. For example, the pattern [abc] will only match a single a, b, or c letter and nothing else.

How do I find the first character in a regular expression?

The regular expression to match String which contains a digit as first character is “^[0-9]. *$”.


1 Answers

I would try and avoid a complicated regex, I would use String.substring() and indexOf(). That is, something like

String name = "Last, First Middle";
int comma = name.indexOf(',');
int lastSpace = name.lastIndexOf(' ');
String lastName = name.substring(0, comma);
String firstName = name.substring(comma + 2, lastSpace);
String middleName = name.substring(lastSpace + 1);
System.out.printf("first='%s' middle='%s' last='%s'%n", firstName,
            middleName, lastName);

Output is

first='First' middle='Middle' last='Last'
like image 170
Elliott Frisch Avatar answered Sep 21 '22 01:09

Elliott Frisch