我知道 $
用于检查 Java 正则表达式中是否有行尾。
对于以下代码:
String test_domain = "http://www.google.com/path\nline2\nline3";
test_domain = test_domain.replaceFirst("(\\.[^:/]+).*$?", "$1");
System.out.println(test_domain);
输出是:
http://www.google.com
line2
line3
我假设模式 (\\.[^:/]+).*$?
匹配第一行,即 http://www.google.com/path
,$1
是 http://www.google.com
。 ?
不情愿地匹配(因此匹配第一行。)
但是,如果我删除模式中的 ?
并实现以下代码:
String test_domain = "http://www.google.com/path\nline2\nline3";
test_domain = test_domain.replaceFirst("(\\.[^:/]+).*$", "$1");
System.out.println(test_domain);
输出是:
http://www.google.com/path
line2
line3
我认为它应该给出结果 http://www.google.com
(\\.[^:/]+)
匹配http://www.google.com
.*$
匹配/path\nline2\nline3
我对正则表达式的误解在哪里?
最佳答案
您有一个多行输入并尝试在您的正则表达式中为每一行使用 anchor $
但不使用 MULTILINE
标志。您所需要的只是正则表达式前面的 (?m)
模式:
String test_domain = "http://www.google.com/path\nline2\nline3";
test_domain = test_domain.replaceFirst("(?m)(\\.[^:/]+).*$", "$1");
System.out.println(test_domain);
这将输出:
http://www.google.com
line2
line3
如果没有 MULTILINE
或 DOTALL
模式,您的正则表达式:(\.[^:/]+).*$
将无法匹配由于存在 .*$
而输入,因为点将不匹配换行符并且 $
(行尾)出现在 2 个换行符之后。
关于java - Java 正则表达式中的新行和美元符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30404224/