Kirmani88 Kirmani88 - 1 month ago 7x
Java Question

Regular Expression for First Name and Last Name in a single field

I have a scenario where user has to enter its first Name and last name in a single field, so there must be a space between 2 names, and after space there must be atleast a character. I tried to using

, but this method returns true if user just enter a space and does not enter anything after that space.

Kindly guide me a way to achieve this. I have also tried to search
Regular Expression
but failed to find any.


Here is the regex and a test:

public void test_firstAndLastName_success() {
  Pattern ptrn = Pattern.compile("(\\w+)\\s+(\\w+)");
  Matcher matcher = ptrn.matcher("FirstName  LastName");
  if (matcher.find()) {
  } else {;

The validation is the matcher returning false on find.

If you do not want to permit multiple spaces (\s+) then either remove + (which will still permit for a single tab) or replace it with a space.