我有一个模式使用^和$来表示行的开头和结尾.
Pattern pattern = Pattern.compile( "^Key2 = (.+)$" );
Run Code Online (Sandbox Code Playgroud)
并输入如下:
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.";
Run Code Online (Sandbox Code Playgroud)
但pattern.matcher( text ).find()回报false.
这不应该工作吗?在Pattern类文档中,摘要指定:
Boundary matchers ^ The beginning of a line $ The end of a line
默认情况下,这些符号与整个输入序列的开头和结尾相匹配.
在相同的Pattern类文档中进一步向下(强调添加):
默认情况下,正则表达式^和$忽略行终止符,并且仅分别匹配整个输入序列的开头和结尾.如果激活MULTILINE模式,则^在输入开始时和任何行终止符之后匹配,但输入结束时除外.当处于MULTILINE模式时,$匹配在行终止符之前或输入序列的结尾.
所以你可以通过编译模式使^和$工作,因为它们在汇总表中有记录Pattern.MULTILINE:
Pattern pattern = Pattern.compile( "^Key2 = (.+)$", Pattern.MULTILINE );
Run Code Online (Sandbox Code Playgroud)