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.

+3


source to share


3 answers


It seemed to me that regular expressions are not very suitable for this case.



String fullName = "This is My Fullname";
int index = fullName.lastIndexOf(' ');
String lastName = fullName.substring(index+1);
String firstName = fullName.substring(0, index);

      

+4


source


You don't need to use RegEx for this purpose. Just split the string into Spaces and use the last element of the array as LastName.

Example



String[] parts = string.split(" ");

      

part [parts.length - 1] - will be LastName

+1


source


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];

      

0


source







All Articles