English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to get the first letter of each word using regular expressions in Java?

The meta-character " \ b " matches word boundaries, [a-zA-Z] matches a character in English letters (two cases). In short, the expression\ \ b [a-zA-Z] Match a single character in English letters, these two cases are both after each word boundary.

Therefore, to retrieve the first letter of each word-

  • Compilecompile()The above expression of the Pattern class method.

  • Bypass the required input string asmatcher()The parameters of the Pattern class obtain the Matcher object.

  • Finally, for each match, by callinggroup()method to get the matched characters.

Example

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FirstLetterExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter sample text: ");
      String data = sc.nextLine();
      String regex = "\\b[a-zA-Z]";
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Create a Matcher object
      Matcher matcher = pattern.matcher(data);
      System.out.println("First letter of each word from the given string: ");
      while(matcher.find()) {
         System.out.print(matcher.group())+" ");
      }
   }
}

Output Result

Enter sample text:
National Intelligence Agency Research & Analysis Wing
First letter of each word from the given string:
N I A R A W
You May Also Like