且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java正则表达式中的新行和美元符号

更新时间:2023-02-22 13:44:47

您的正则表达式与输入字符串不匹配.实际上,$完全匹配字符串的末尾(在line3的末尾).由于您未使用s标志,因此.无法到达那里.

Your regex does not match the input string.In fact, $ matches exactly the end of string (at the end of line3). Since you are not using an s flag, the . cannot get there.

更多,行/字符串锚点的$末尾不能带有?量词.对于正则表达式引擎没有意义,在Java中被忽略.

More, the $ end of line/string anchor cannot have ? quantifier after it. It makes no sense for the regex engine, and is ignored in Java.

要使其完全起作用,如果只想返回http://www.google.com,则需要使用s标志:

To make it work at all, you need to use s flag if you want to just return http://www.google.com:

String test_domain = "http://www.google.com/path\nline2\nline3";
test_domain = test_domain.replaceFirst("(?s)(\\.[^:/]+).*$", "$1");
System.out.println(test_domain);

此演示的输出:

http://www.google.com

使用多行(?m)标志,正则表达式将处理每行以查找文字.,然后查找除:/以外的其他字符序列.找到这些字符之一后,该行上的其余字符将被忽略.

With a multiline (?m) flag, the regex will process each line looking for a literal . and then a sequence of characters other than : and /. When one of these characters is found, the rest of characters on that line will be omitted.

    String test_domain = "http://www.google.com/path\nline2\nline3";
    test_domain = test_domain.replaceFirst("(?m)(\\.[^:/]+).*$", "$1");
    System.out.println(test_domain);

此IDEONE演示的输出:

http://www.google.com
line2
line3