
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
Matching Multiple Lines in Java Regular Expressions
To match/search a input data with multiple lines −
Get the input string.
Split it into an array of tokens by passing "\r?\n" as parameter to the split method.
Compile the required regular expression using the compile() method of the pattern class.
Retrieve the matcher object using the matcher() method.
In the for loop find matches in the each element (new line) of the array using the find() method.
Reset the input of the matcher to the next element of the array using the reset() method.
Example
import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatchingText{ public static void main(String[] args) { String input = "sample text line 1 \n line2 353 35 63 \n line 3 53 35"; String regex = "\d"; String[] strArray = input.split("\r?\n"); //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(input); for (int i = 0; i < strArray.length; i++) { matcher.reset(strArray[i]); System.out.println("Line:: "+(i+1)); while (matcher.find()) { System.out.print(matcher.group()+" "); } System.out.println(); } } }
Output
Line:: 1 1 Line:: 2 2 3 5 3 3 5 6 3 Line:: 3 3 5 3 3 5
Advertisements