Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex does not match newline

Tags:

java

regex

My code is as follows:

public class Test {
    static String REGEX = ".*([ |\t|\r\n|\r|\n]).*";
    static String st = "abcd\r\nefgh";

    public static void main(String args[]){
        System.out.println(st.matches(REGEX));
    }
}

The code outputs false. In any other cases it matches as expected, but I can't figure out what the problem here is.

like image 459
Dragos Avatar asked Jul 13 '15 08:07

Dragos


People also ask

How to match new line in regex Java?

The character \n matches the newline character.

How do you match a line in terminators regex?

By default, the regular expressions ^ and $ ignore line terminators and only match at the beginning and the end, respectively, of the entire input sequence. If MULTILINE mode is activated then ^ matches at the beginning of input and after any line terminator except at the end of input.


1 Answers

You need to remove the character class.

static String REGEX = ".*( |\t|\r\n|\r|\n).*";

You can't put \r\n inside a character class. If you do that, it would be treated as \r, \n as two separate items which in-turn matches either \r or \n. You already know that .* won't match any line breaks so, .* matches the first part and the next char class would match a single character ie, \r. Now the following character is \n which won't be matched by .*, so your regex got failed.

like image 117
Avinash Raj Avatar answered Oct 05 '22 00:10

Avinash Raj