Regular Expressions With Java's Text Blocks / Multiline Strings

A Java regex pattern "java or duke" matches on a regular Java string:


import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.regex.Pattern;

import org.junit.jupiter.api.Test;

public class RegexTest {

    @Test
    public void singleLine(){
        var pattern = Pattern.compile(".*(java|duke).*");
        var text = "java duke";
        assertTrue(pattern.matcher(text).matches());
        
    }
    

...but fails on multiline Java String / Text Blocks:


@Test
public void multiLine() {
    var pattern = Pattern.compile(".*(java|duke).*");
    var message = """
        java
        duke
    """;
    assertFalse(pattern.matcher(message).matches());
}

The option Pattern.DOTALL:

(...) In dotall mode, the expression . matches any character, including a line terminator. By default this expression does not match line terminators (...)

makes the regular expression work on multiline strings:


@Test
public void multiLineDotAll() {
    var pattern = Pattern.compile(".*(java|duke).*",Pattern.DOTALL);
    var message = """
        java
        duke
    """;
    assertTrue(pattern.matcher(message).matches());
}

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments
License