给出以下表达式:
Pattern.compile("^Test.*\n").matcher("Test 123\nNothing\nTest 2\n").replaceAll("foo\n")
这会产生:
"foo\nNothing\nTest 2\n"
对我来说。我预计最后一行也会替换为foo\n
,因为输入字符串中Test 2
之前就有一个换行符。
为什么正则表达式不匹配?
答案 0 :(得分:1)
您必须在模式中添加多行标记:Pattern.MULTILINE
。
Pattern.compile("^Test.*\n", Pattern.MULTILINE).matcher("Test 123\nNothing\nTest 2\n").replaceAll("foo\n")
默认情况下,匹配仅为单行。有关更多信息,请参阅the javadoc
答案 1 :(得分:1)
在正则表达式的开头,你有一个^
符号,通常将正则表达式固定在测试字符串的开头。您需要指定多行正则表达式选项(Oracle Documentation link),以使其适用于每行的开头。
试试这个(我已将线条拆分为易读性,随时可以回复):
Pattern.compile("^Test.*\n", Pattern.MULTILINE)
.matcher("Test 123\nNothing\nTest 2\n")
.replaceAll("foo\n")
不幸的是,我目前没有设置Java环境,因此我无法自行检查。