Regex to Split Full Name
I am looking for a regex to be used in my Java application to split the full name into first and last name parts.
The full name will always be separated by "" (space as separator). some name can consist of middle name, but they can be combined with FirstName, I only want to separate the Last name as a separate group.
For example :
"This is My Fullname"
LastName = Fullname
FirstName = This is My
So the logic is that after Last WhiteSpace it counts as LastName and everything before that as FirstName.
source to share
You will probably need a look ahead approach since you don't know the number of spaces in your input. The problem is with groups with an unknown number of items. For example. ([^]) ([^]) ([^]) ([^]) and referencing $ 3 and $ 4 will work on your 4-element string, but not many elements. And ([^]) * ([^]) will not be able to refer to groups.
But in this simple case, I would say the easiest is to use string splitting and take the last 2 elements:
String inputString = "This is My Fullname";
String[] splitText = inputString.split(" ");
String firstName = splitText[splitText.length-2];
String lastName = splitText[splitText.length-1];
source to share