
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Regular Expression Metacharacter in Java
The subexpression/metacharacter “\b” matches the word boundaries when outside the brackets. Matches the backspace (0x08) when inside the brackets.
Example 1
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "\bbecause\b"; Scanner sc = new Scanner(System.in); System.out.println("Enter a string: "); String input = sc.nextLine(); Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); int count = 0; while(m.find()) { count ++; } System.out.println("Number of matches: "+count); } }
Output
Enter a string: A sentence doesn't end with because because, because is a conjunction Number of matches: 3
Example 2
The following Java example reads a string value from the user and prints the number of word boundaries.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main( String args[] ) { System.out.println("Enter input 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(count); } }
Output
Enter input string: Hello how are you welcome to Tutorialspoint 14
Advertisements