Java 正则表达式将所有内容匹配到一个空行
我已经试了几个小时了,我肯定我错过了一些简单的东西。 我正在尝试用Java创建一个方法,它获取一些文本并提取其中的一部分 我想匹配从“注释”到后面第一个空行的所有内容 示例输入Java 正则表达式将所有内容匹配到一个空行,java,regex,Java,Regex,我已经试了几个小时了,我肯定我错过了一些简单的东西。 我正在尝试用Java创建一个方法,它获取一些文本并提取其中的一部分 我想匹配从“注释”到后面第一个空行的所有内容 示例输入 Some info about stuff Notes: THis is a note about other stuff So is this And this This is something else 输入可以是不同长度的,因此也可以是 BLabla Notes: Hello hello
Some info about stuff
Notes: THis is a note about other stuff
So is this
And this
This is something else
输入可以是不同长度的,因此也可以是
BLabla
Notes: Hello hello
So is this
And this
And this too
also
Now I have something else to say
所需产出:
例1
Notes: THis is a note about stuff
So is this
And this
例2
Notes: Hello hello
So is this
And this
And this too
also
我试过:
public static String NotesExtractor(String str){
String mynotes=null;
str=str+"\n\n"+"ENDOFLINE";
Pattern Notesmatch_pattern = Pattern.compile("Notes:(.*?)^\\s*$",Pattern.DOTALL);
Matcher Notesmatchermatch_pattern = Notesmatch_pattern.matcher(str);
if (Notesmatchermatch_pattern.find()) {
String h = Notesmatchermatch_pattern.group(1).trim();
mynotes=h;
}
mynotes=mynotes.replaceAll("^\\n", "").trim();
return mynotes;
}
但是我没有找到任何匹配项,我也不知道为什么。你可以使用这个正则表达式
(?s)Notes.*?(?=\n\n)
Java代码
输入可以是不同长度的,因此确实需要一种方法将第一条黑线与不同长度的输入匹配起来。所以我想我需要使用Patter.DOTALL。我已经修改了我的问题来澄清这一点。@SebastianZeki您可以从用户那里获取信息。。我不明白您在暗示什么,我表示歉意。它确实很好用。我仍然不能得到我想要的输出,但这显然不是正则表达式的问题,所以给定正则表达式是正确的awarded@SebastianZeki是的..也许你需要重新检查你的代码,如果你使用
replaceAll
,则在Notes:
之前和两行换行之后定位零件。尝试模式字符串:“(?s^.*?(?=Notes:)|(?:\\r?\\n){2}.*”
。您可以使用DOTALL
而不是(?s)
。
String line = "Some info about stuff\nNotes: THis is a note about other stuff\nSo is this\n And this\n\nThis is something else";
String pattern = "(?s)Notes.*?(?=\n\n|$)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println(m.group());
}