
- Java Tutorial
- Java - Home
- Java - Overview
- Java - Environment Setup
- Java - Basic Syntax
- Java - Object & Classes
- Java - Constructors
- Java - Basic Datatypes
- Java - Variable Types
- Java - Modifier Types
- Java - Basic Operators
- Java - Loop Control
- Java - Decision Making
- Java - Numbers
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Regular Expressions
- Java - Methods
- Java - Files and I/O
- Java - Exceptions
- Java - Inner classes
- Java Object Oriented
- Java - Inheritance
- Java - Overriding
- Java - Polymorphism
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java Advanced
- Java - Data Structures
- Java - Collections
- Java - Generics
- Java - Serialization
- Java - Networking
- Java - Sending Email
- Java - Multithreading
- Java - Applet Basics
- Java - Documentation
- Java Useful Resources
- Java - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
Matching a whole word Java Regular expressions:
The meta character "\b" matches word boundaries. i.e. it matches before the first and after the last word characters and between word and non-word characters.
Therefore to match a whole word you need to surround it between the word boundary meta characters as −
\btest\b
Example
Following Java example counts and prints the number of occurrences of the word test in the given input string.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter input text: "); String input = sc.nextLine(); String regex = "\btest\b"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(input); int count =0; while (matcher.find()) { count++; } System.out.println("Number of occurrences of the word test : "+count); } }
Output
Enter input text: sample data: test test test Number of occurrences of the word test : 3
- Related Articles
- Matching multiple lines in Java regular expressions
- Which package is used for pattern matching with regular expressions in java?
- Java Regular Expressions Tutorial
- Java regular expressions sample examples
- Possessive quantifiers Java Regular expressions
- Java Regular expressions Logical operators
- Reluctant quantifiers Java Regular expressions
- A greedy qualifier in Java Regular Expressions
- A Reluctant qualifier in Java Regular Expressions
- Greedy quantifiers Java Regular expressions in java.
- Use a character class in Java Regular Expressions
- Validate Phone with Java Regular Expressions
- Back references in Java regular expressions
- Regular Expressions syntax in Java Regex
- Regex quantifiers in Java Regular Expressions

Advertisements