Home » Core Java » util » regex » Line ending matching example

About Ilias Tsagklis

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

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments