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.
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)
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.
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.
The regular expression to match String which contains a digit as first character is “^[0-9]. *$”.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With