正则表达式的边界匹配符(^)和($)不起作用,无法匹配行首和行尾。

7

我有一个用^和$表示行首和行尾的模式。

Pattern pattern = Pattern.compile( "^Key2 = (.+)$" );

并且像这样输入:

String text = "Key1 = Twas brillig, and the slithy toves"
  + "\nKey2 = Did gyre and gimble in the wabe."
  + "\nKey3 = All mimsy were the borogroves."
  + "\nKey4 = And the mome raths outgrabe.";

但是pattern.matcher(text).find()返回false
这不应该起作用吗?在Pattern类文档中,概述指定:
边界匹配器 ^ 行的开头 $ 行的结尾
1个回答

9
默认情况下,这些符号与整个输入序列的开头和结尾匹配。在同一模式类文档中进一步阅读(已强调):如果激活了MULTILINE模式,则^匹配输入的开头和除了输入结束处以外的任何行终止符之后。当MULTILINE模式下$匹配行终止符或输入序列的结尾之前。因此,通过使用Pattern.MULTILINE编译模式,您可以使^和$按照摘要表中记录的方式工作。
Pattern pattern = Pattern.compile( "^Key2 = (.+)$", Pattern.MULTILINE );

太棒了 :) 我以前也曾经为此苦恼过。 - AbtPst
1
@AbtPst - 我也是。Javadoc 中的细节被埋藏了起来,摘要需要简要澄清。这些年来,我已经遇到、解决并忘记了这个问题多次。下一次就会有这个 StackOverflow 问题! - Andy Thomas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接