Pattern.UNIX_LINES in regex with Java

后端 未结 2 1249
无人共我
无人共我 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.

提交回复
热议问题