- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use Pattern class to match in Java
The representation of the regular expressions are available in the java.util.regex.Pattern class. This class basically defines a pattern that is used by the regex engine.
A program that demonstrates using the Pattern class to match in Java is given as follows −
Example
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo { public static void main(String args[]) { Pattern p = Pattern.compile("p+"); Matcher m = p.matcher("apples and peaches are tasty"); System.out.println("The input string is: apples and peaches are tasty"); System.out.println("The Regex is: p+ "); System.out.println(); while (m.find()) { System.out.println("Match: " + m.group()); } } }
Output
The input string is: apples and peaches are tasty The Regex is: p+ Match: pp Match: p
Now let us understand the above program.
The subsequence “p+” is searched in the string sequence "apples and peaches are tasty". The Pattern class defines the pattern that is used by the regex engine i.e. “p+”. The find() method is used to find if the subsequence i.e. p followed by any number of p is in the input sequence and the required result is printed. A code snippet which demonstrates this is as follows −
Pattern p = Pattern.compile("p+"); Matcher m = p.matcher("apples and peaches are tasty"); System.out.println("The input string is: apples and peaches are tasty"); System.out.println("The Regex is: p+ "); System.out.println(); while (m.find()) { System.out.println("Match: " + m.group()); }
Advertisements
To Continue Learning Please Login
Login with Google