我有一个regex来匹配一行并删除它。一切都在它下面(并保持在它之上的一切)。
两个部分问: 1)为什么这个模式不能匹配下面给定的字符串文本? 2)如何确保只匹配一行而不是多行?-必须在同一单行上找到该模式。
String text = "Keep this.\n\n\nPlease match junkhere this t-h-i-s is missing.\n"
+ "Everything should be deleted here but don't match this on this line" + "\n\n";
Pattern p = Pattern.compile("^(Please(\\s)(match)(\\s)(.*?)\\sthis\\s(.*))$", Pattern.DOTALL );
Matcher m = p.matcher(text);
if (m.find()) {
text = (m.replaceAll("")).replaceAll("[\n]+$", ""); // remove everything below at and below "Please match ... this"
System.out.println(text);
}预期产出:
留着这个吧。
发布于 2014-02-21 20:32:37
你让你的生活变得复杂..。
首先,正如我在评论中所说的,使用Pattern.MULTILINE。
然后,若要从匹配的开头截断字符串,请使用.substring()
final Pattern p = Pattern.compile("^Please\\s+match\\b.*?this",
Pattern.MULTILINE);
final Matcher m = p.matcher(input);
return m.find() ? input.substring(0, m.start()) : input;发布于 2014-02-21 20:22:16
删除DOTALL以确保与单行匹配,并将\s转换为" "
Pattern p = Pattern.compile("^(Please( )(match)( )(.*?) this (.*))$");DOTALL也使点匹配换行符。\s可以匹配任何空格,包括新行。https://stackoverflow.com/questions/21944361
复制相似问题