Pattern.UNIX_LINES in regex with Java

后端 未结 2 1247
无人共我
无人共我 2021-01-21 20:20

Hi from the java doc here the following:

UNIX_LINES

public static final int UNIX_LINES

Enables Unix

相关标签:
2条回答
  • 2021-01-21 20:47

    As far as how they apply specifically to regex behavior; ., ^, and $ depend on the definition of a line feed to function.

    • . matches anything but a line break
    • ^ can match the beginning of a line
    • $ can match the end of a line.

    Each of these depend on the correct definition of where a line terminates. The UNIX_LINES setting instructs it to strictly define the line terminator per the standard Unix definition. By default, it defines it more broadly, as seen in the Pattern docs

    As far as matching "abc\n", I assume you are using Pattern.matches, or something like it, which must match the entire input? ^ and $ are zero-width. They can match on either side of a newline, but will not consume the newline character. You can consume the \n by simply putting it in your pattern, such as abc\n, or you could also use the $ character somewhat as you indicated, like abc\n$, or if you're feeling frisky (?m)abc$$$$\n$$.

    DOTALL and MULTILINE modes might also be of use to you, depending on what you are trying to accomplish.

    0 讨论(0)
  • 2021-01-21 20:59

    I will try to explain it on . since same rule apply for ^ and $.

    Normally dot . matches every character except new line. In Unix only \n is new line mark, so other characters like carriage return \r are threated as normal characters.

    Take a look at this String "A\r\nB\rC\nD". If you will try to find match for regex like.+ using

    String data = "A\r\nB\rC\nD";
    System.out.println(data);
    Matcher m = Pattern.compile(".+").matcher(data);
    while (m.find()) {
        System.out.println("["+m.group()+"]");
    }
    

    you will get

    [A]
    [B]
    [C]
    [D]
    

    but if add flag Pattern.UNIX_LINES characters like \r will also be possible match for . and output will change into

    [A
    ]
    [B
    C]
    [D]
    

    So first match is [A\r], second [B\rC] and third [C]

    0 讨论(0)
提交回复
热议问题