Skip to content
Related Articles

Related Articles

Improve Article

Print first letter of each word in a string using regex

  • Last Updated : 11 Dec, 2018
Geek Week

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.


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.


// 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 
    public static void main(String[] args) 
        String s1 = "Geeks for Geeks";
        String s2 = "A Computer Science Portal for Geeks";
        Pattern p = Pattern.compile("\\b[a-zA-Z]");
        Matcher m1 = p.matcher(s1);
        Matcher m2 = p.matcher(s2);
        System.out.println("First letter of each word from string \"" + s1 + "\" : ");
        while (m1.find())
        System.out.println("First letter of each word from string \"" + s2 + "\" : ");
        while (m2.find()) 


First letter of each word from string "Geeks for Geeks" : 
First letter of each word from string "A Computer Science Portal for Geeks" : 

Next Article: Extracting each word from a String using Regex in Java

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :