Matching (optional) White space with String.splitregular expression
Do you have a space after the comma on your input, you can change your regular expression splitfrom
String str[] = name.split(",");
to
String str[] = name.split(",\\s*");
to match and remove extra white space. After I made the above change, I ran your code and received the (expected) output
Doe, John
J. Doe
Trim the leading white space
, trim str[1] , ,
sb.append(str[1].trim().charAt(0));
Pattern
- regex Pattern Matcher,
private static Pattern pattern = Pattern.compile("(.+),\\s*(.).*");
public static String formatName(String name) {
Matcher m = pattern.matcher(name);
if (m.matches()) {
return String.format("%s. %s", m.group(2), m.group(1));
}
return name;
}