Get the first letter of each word in a string using regex in Java
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 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
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.
Recommended Posts:
- Print first letter of each word in a string using regex
- Extracting each word from a String using Regex in Java
- String containing first letter of every word in a given string with spaces
- Count of words whose i-th letter is either (i-1)-th, i-th, or (i+1)-th letter of given word
- Check if a string contains only alphabets in Java using Regex
- First uppercase letter in a string (Iterative and Recursive)
- Program to find all match of a regex in a string
- Get K-th letter of the decoded string formed by repeating substrings
- Check if the string contains consecutive letters and each letter occurs exactly once
- Number of positions where a letter can be inserted such that a string becomes palindrome
- Extract maximum numeric value from a given string | Set 2 (Regex approach)
- Python Regex to extract maximum numeric value from a string
- Regex Boundary Matchers in Java
- Java | Removing whitespaces using Regex
- Count occurrences of a given character using Regex in Java



