Computer >> Computer tutorials >  >> Programming >> Java

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


The metacharacter “\b” matches for the word boundaries and [a-zA-Z] matches one character from the English alphabet (both cases). In short, the expression \\b[a-zA-Z] matches one single character from the English alphabet, both cases after every word boundary.

Therefore, to retrieve the first letter of each word −

  • Compile the above expression of the compile() method of the Pattern class.

  • Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class.

  • Finally, for each match get the matched characters by invoking the group() method.

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]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating 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

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