Java Regex does not match newline

My code looks like this:

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));
    }
}

      

Code output false

. In any other case, it is as expected, but I cannot figure out what the problem is.

+3


source to share


2 answers


UPDATE

Based on your comments, you need something like this:

.*(?:[ \r\n\t].*)+

      

EXPLANATION

In simple words, this is a regular expression that matches a string , then 1 or more lines. Or just multi-line text .

  • .*

    - 0 or more characters except newline
  • (?:[ \r\n\t].*)+

    - non-capturing group that matches 1 or more times in the sequence
    • [ \r\n\t]

      - either a space, or \r

      or \n

      or\t

    • .*

      - 0 or more characters except newline

Watch the demo

Original Answer



You can fix your template in two ways:

String REGEX = ".*(?:\r\n|[ \t\r\n]).*";

      

This is how we match a sequence \r\n

or any character in a character class.

Or (since a character class only matches 1 character, we can add +

after it to make 1 or more:

String REGEX = ".*[ \t\r\n]+.*";

      

See IDEONE demo

Note that it is not recommended to use single interleaved characters as this degrades performance.

Also note that capture groups should not be overestimated. If you do not plan to use the contents of the group, use non-capture ( (?:...)

) groups or delete them.

+1


source


You need to remove the character class.

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

      



You cannot put \r\n

inside a character class. If you do, it will be treated as \r

, \n

as two separate elements, which in turn correspond to either \r

or \n

. You already know that .*

it won't match line breaks, so it .*

matches the first part, and the next char class will match one character, i.e. \r

... Now the next character \n

that won't match .*

, which is why your regex got a crash.

+5


source







All Articles