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.
The character \n matches the newline character.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With