- Trending Categories
- 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 find() to find multiple subsequences in Java
The find() method finds the multiple subsequences in an input sequence that matches the pattern required. This method is available in the Matcher class that is available in the java.util.regex package
A program that uses the find() method to find multiple subsequence 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("the"); Matcher m = p.matcher("eclipses of the sun and the moon"); System.out.println("Subsequence: the"); System.out.println("Sequence: eclipses of the sun and the moon"); System.out.println(); while (m.find()) { System.out.println("the found at index " + m.start()); } } }
Output
Subsequence: the Sequence: eclipses of the sun and the moon the found at index 12 the found at index 24
Now let us understand the above program.
The subsequence “the” is searched in the string sequence "eclipses of the sun and the moon". Then the find() method is used to find if the subsequence is in the input sequence any number of times and the required result is printed. A code snippet which demonstrates this is as follows:
Pattern p = Pattern.compile("the"); Matcher m = p.matcher("eclipses of the sun and the moon"); System.out.println("Subsequence: the" ); System.out.println("Sequence: eclipses of the sun and the moon" ); System.out.println(); while (m.find()) { System.out.println("the found at index " + m.start()); }
Advertisements