How to match word boundaries using Java RegEx?


You can match the word boundaries using the meta character “\b”.

Example 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "\b";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("Number of word boundaries: "+count);
   }
}

Output

Enter a String
this is a sample text
Number of word boundaries: 10

Example 2

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

Updated on: 19-Nov-2019

269 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements