我有以下文件内容,我正在尝试匹配下面解释的注册表:
-- file.txt (doesn't match single/in-line text) --
test On blah more blah wrote:
blah blah blah
blah blah
blah
---------------
如果我从上面读取文件内容到String并尝试匹配“On ... write:”部分我无法得到匹配:
// String text = <file contents from above>
Pattern PATTERN = Pattern.compile("^(On\\s(.+)wrote:)$");
Matcher m = PATTERN.matcher(text);
if (m.find()) {
System.out.println("Never gets HERE???");
// TODO: Strip out all characters after the match and any \s or \n before
}
基本上我想要以下输出:
-- file2.txt --
test
---------------
答案 0 :(得分:1)
也许这可以帮助您获得所需的结果:
String text = "test On blah more blah wrote:\n"
+ "blah blah blah\nblah blah\nblah\n";
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Pattern PATTERN = Pattern.compile("^(.*?)\\s*On\\s(.+)wrote:$",
Pattern.MULTILINE);
Matcher m = PATTERN.matcher(text);
if (m.find()) {
pw.println(m.group(1));
}
pw.close();
System.out.println(sw);
Pattern.MULTILINE javadoc:在多行模式下,表达式^和$分别在行终止符之后或之前匹配 ...我还添加了匹配所有内容的(。*?)在第一个“开”之前。
答案 1 :(得分:0)
由于您要查找的模式无法启动该行,因此请删除^
。这匹配行的开头,但您要查找的行以“test”开头。
但是,如果您想捕获“测试”,请在(\\w+)\\s
之后插入^
以形成^(\\w+)\\s(On\\s(.+)wrote:)$