Java regex match single line

public class TestJavaRegexMatchingSingleLine {

    private static final String WINDOWS_LINES = "first line\r\nsecond line \r\n third line";
    private static final String UNIX_LINES = "first line\rsecond line \r third line";

    @Test
    public void shouldNotFindMatching() throws Exception {
        assertFalse(Pattern.compile("^.*$").matcher(UNIX_LINES).find()); // dot '.' by default does not match \r not \r\n; anchors ^ and $ indicate begin and end of input string
        assertFalse(Pattern.compile("^.*$").matcher(WINDOWS_LINES).find());
    }

    @Test
    public void shouldFindWindowsLines() throws Exception {
        shouldFindLinesUsingMultiLineMode(WINDOWS_LINES);
    }

    @Test
    public void shouldFindUnixLines() throws Exception {
        shouldFindLinesUsingMultiLineMode(UNIX_LINES);
    }

    private void shouldFindLinesUsingMultiLineMode(String multiLineText) {
        Matcher m = Pattern.compile("(?m)^.*$").matcher(multiLineText); // (?m) MULTI-LINE mode - when explicitly enabled - makes anchors ^ and $ indicate begin and end of line
        List<String> lines = new ArrayList<String>();
        while (m.find()) {
            lines.add(m.group());
            System.out.println("line = '" + m.group() + "'");
        }
        assertEquals(3, lines.size());
        assertEquals("first line", lines.get(0));
        assertEquals("second line ", lines.get(1));
        assertEquals(" third line", lines.get(2));
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s