regex
Line ending matching example
With this example we are going to demonstrate how to check a line ending matching. We are using Patterns and Matchers against each pattern. In short, to check a line ending matching you should:
- Create a String array that contains the patterns to be used.
- For every pattern in the array compile it to a Pattern, using
compile(string regex)API method of Pattern. - Use
matcher(CharSequence input)API method of Pattern to get a Matcher that will match the given input String against this pattern. - Use
find()API method of Matcher to find the next subsequence of the input sequence that matches the pattern. - Then compile it to a Pattern, using
compile(String regex, int flags)API method of Pattern with specified pattern modes as flags. - Use
matcher(CharSequence input)API method of Pattern to get a matcher that will match the given input String against this pattern.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
import java.util.regex.Pattern;
/*
** Show line ending matching using RE class.
*/
public class LineEndings {
public static void main(String[] argv) {
String inputStr = "I dream of enginesnmore engines, all day long";
System.out.println("INPUT: " + inputStr);
System.out.println();
String[] pattern = {"engines.more engines", "engines$"};
for (int i = 0; i < pattern.length; i++) {
System.out.println("PATTERN " + pattern[i]);
boolean found;
Pattern pattern1l = Pattern.compile(pattern[i]);
found = pattern1l.matcher(inputStr).find();
System.out.println("DEFAULT match " + found);
Pattern patternml = Pattern.compile(pattern[i], Pattern.DOTALL | Pattern.MULTILINE);
found = patternml.matcher(inputStr).find();
System.out.println("MultiLine match " + found);
}
}
}
Output:
INPUT: I dream of engines
more engines, all day long
PATTERN engines.more engines
DEFAULT match false
MultiLine match true
PATTERN engines$
DEFAULT match false
MultiLine match true
This was an example of how to check a line ending matching in Java.

