![]() |
In Java string manipulation, searching for specific words is a fundamental task. Regular expressions (regex) offer a powerful and flexible approach to achieve this search. It matches the patterns simply by comparing substrings. In this article, we will learn how to search for a particular word in a string using regex in Java. Regular Expressions:
Word Boundaries:
Step-by-Step ImplementationStep 1: Import java.util.regeximport java.util.regex.*;
Step 2: Compile the Regex Pattern
String word = "Java"; // Word to search for Step 3: Create a Matcher
String text = "This is a string containing the word Java."; Step 4: Iterate and Process Matches
Example with output formatting: while (matcher.find()) { Step 5: Handling No Matches
Program to Search a Particular Word in a String Using Regex in JavaJava
Output
Found word "Java" at index [37, 40] Found word "Java" at index [55, 58] |
Reffered: https://www.geeksforgeeks.org
Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |