Open In App

Get the first letter of each word in a string using regex in Java

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given a string, extract the first letter of each word in it. “Words” are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples:

Input : Geeks for geeks
Output :Gfg
        
Input : United Kingdom
Output : UK

Below is the Regular expression to extract the first letter of each word. It uses ‘/b'(one of boundary matchers). Please refer How to write Regular Expressions? to learn it.

\b[a-zA-Z]

Java




// Java program to demonstrate extracting first
// letter of each word using Regex
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class Test {
    static void printFirst(String s)
    {
        Pattern p = Pattern.compile("\\b[a-zA-Z]");
        Matcher m = p.matcher(s);
 
        while (m.find())
            System.out.print(m.group());
 
        System.out.println();
    }
 
    public static void main(String[] args)
    {
        String s1 = "Geeks for Geeks";
        String s2 = "A Computer Science Portal for Geeks";
        printFirst(s1);
        printFirst(s2);
    }
}


Output

GfG
ACSPfG

Last Updated : 13 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads