[英]Matching non multiline regular expression
我具有以下文件內容,並且我試圖匹配下面說明的reg:
-- file.txt (doesn't match single/in-line text) --
test On blah more blah wrote:
blah blah blah
blah blah
blah
---------------
如果我從上方將文件內容讀取為字符串,然后嘗試匹配“ On ... wrote:”部分,則無法找到匹配項:
// 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
---------------
也許這可以幫助您獲得所需的結果:
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: 在多行模式下,表達式^和$分別在行終止符之后或之前匹配 。我還添加了(。*?),它匹配第一個“開”之前的所有內容。
由於您要查找的模式無法開始,因此請刪除^
。 這與行的開頭匹配,但是您要查找的行以單詞“ test”開頭。
但是,如果要捕獲“測試”,則在^
后面插入(\\\\w+)\\\\s
,以形成^(\\\\w+)\\\\s(On\\\\s(.+)wrote:)$
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.