Given a string, the task is to extract and print the first letter of each word using a regular expression. Here, a word is considered a sequence of English alphabetic characters (a-z or A-Z). The regular expression \b[a-zA-Z] can be used to find the first alphabetic character at each word boundary.
- Java requires \\b instead of \b inside a string literal.
- Matcher.find() is used to locate each occurrence.
Illustration
Input: "Geeks for geeks"
Output: GfgInput: "United Kingdom"
Output: UK
How It Works
- \b represents a word boundary.
- [a-zA-Z] matches one uppercase or lowercase English letter.
- Together, \b[a-zA-Z] matches the first letter of each word.
- In a Java string literal, \b must be written as \\b because the backslash must be escaped.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GFG {
public static void main(String[] args) {
String str = "Geeks for Geeks";
// Create regex pattern to match the first
// letter of each word
Pattern pattern = Pattern.compile("\\b[a-zA-Z]");
// Create Matcher for the input string
Matcher matcher = pattern.matcher(str);
System.out.print("First letters: ");
// Find and print the first letter of each word
while (matcher.find()) {
System.out.print(matcher.group());
}
}
}
Output
First letters: GfG
Explanation
- Pattern.compile("\\b[a-zA-Z]") creates the regular expression pattern.
- pattern.matcher(str) creates a Matcher for the given string.
- matcher.find() searches for the next matching first letter.
- matcher.group() returns the matched character.
- The loop continues until all word-start letters are found.