Kirmani88 Kirmani88 - 2 months ago 11
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

contains("")
, 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.

Answer

Here is the regex and a test:

@Test
public void test_firstAndLastName_success() {
  Pattern ptrn = Pattern.compile("(\\w+)\\s+(\\w+)");
  Matcher matcher = ptrn.matcher("FirstName  LastName");
  if (matcher.find()) {
    Assert.assertEquals("FirstName", matcher.group(1));
    Assert.assertEquals("LastName", matcher.group(2));
  } else {
    Assert.fail();
  }
}

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.

Comments