Skip to content
Advertisement

How do I get the first and last initial/character from a name string

I am trying to extract the first character of both first and last name from a string but have had no luck so far.( tried searching multiple solutiosn online, no luck either) So for example, if this is the string:

name = A A BCD EFG

I want to display just A and E ( say AE). I am trying to figure out if theres an easier way to do this. The regex I am using, does get me the first character, but doesnt work for the last character, it returns (AEFG) ,aka the whole of last name instead. Is there a way to go about this? Here’s my code:

 String lastName = "";
        String firstName= "";

        if(name.split("\w+").length>1){

            lastName = name.substring(name.lastIndexOf(" ")+1,1);
            firstName = name.substring(0,1);
        }
        else{
            firstName = name;
        }
        String completeInitials = firstName + " " + lastName;

Advertisement

Answer

You can use this regex to capture the first letter of first name in group1 and first letter of lastname in group2 and replace whole match with $1$2 to get the desired string.

^s*([a-zA-Z]).*s+([a-zA-Z])S+$

Explanation:

  • ^ – Start of string
  • s* – Matches optional whitespace(s)
  • ([a-zA-Z]) – Matches the first letter of firstname and captures it in group1
  • .*s+ – Here .* matches any text greedily and s+ ensures it matches the last whitespace just before last name
  • ([a-zA-Z]) – This captures the first letter of lastname and captures it in group2
  • S+$ – Matches remaining part of lastname and end of input

Regex Demo

Java code,

String s = "A A BCD EFG";
System.out.println(s.replaceAll("^\s*([a-zA-Z]).*\s+([a-zA-Z])\S+$", "$1$2"));

Prints,

AE

Edit: To convert/ensure the replaced text to upper case, in case the name is in lower case letters, in PCRE based regex you can use U just before the replacement as U$1$2 but as this post is in Java, it won’t work that way and hence you can use .toUpperCase()

Demo for ensuring the replaced text is in upper case

Java code for same would be to use .toUpperCase()

String s = "a A BCD eFG";
System.out.println(s.replaceAll("^\s*([a-zA-Z]).*\s+([a-zA-Z])\S+$", "$1$2").toUpperCase());

Prints in upper case despite the input string in lower case,

AE
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement