Getting first letter of each word in a String using regex in Java



A word is contiguous series of alphabetic characters. Using regex, we need to search the boundary character to be between A to Z or a to z. Consider the following cases −

Input: Hello World
Output: H W

Input: Welcome to world of Regex
Output: W t w o R

We'll use the regex as "\b[a-zA-Z]" where \b signifies the boundary matchers. See the example −

Example

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tester {
   public static void main(String[] args) {

      String input1 = "Hello World";
      String input2 = "Welcome to world of Regex";
      Pattern p = Pattern.compile("\b[a-zA-Z]");

      Matcher m = p.matcher(input1);
      System.out.println("Input: " + input1);
      System.out.print("Output: ");
      while (m.find()){
         System.out.print(m.group() + " ");
      }
      System.out.println("
");       m = p.matcher(input2);       System.out.println("Input: " + input2);       System.out.print("Output: ");       while (m.find()){          System.out.print(m.group() + " ");       }       System.out.println();    } }

Output

Input: Hello World
Output: H W

Input: Welcome to world of Regex
Output: W t w o R

Advertisements