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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button