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";

    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

    public void shouldFindWindowsLines() throws Exception {

    public void shouldFindUnixLines() throws Exception {

    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()) {
            System.out.println("line = '" + + "'");
        assertEquals(3, lines.size());
        assertEquals("first line", lines.get(0));
        assertEquals("second line ", lines.get(1));
        assertEquals(" third line", lines.get(2));

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s