如何匹配正则表达式的单行?

时间:2014-02-21 20:19:05

标签: java regex

我有regex来匹配一行并删除它。一切都低于它(并保持高于它)。

Two Part Ask:

1) Why won't this pattern match the given String text below?
2) How can I be sure to just match on a single line and not multiple lines?
   - The pattern has to be found on the same single line.
    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);
    }

预期产出:

  

保持这一点。

2 个答案:

答案 0 :(得分:2)

你的生活变得复杂......

首先,正如我在评论中所说,使用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;

答案 1 :(得分:1)

删除DOTALL以确保在一行上匹配并将\s转换为" "

Pattern p = Pattern.compile("^(Please( )(match)( )(.*?) this (.*))$");
  • DOTALL也会使点匹配换行符
  • \s可以匹配任何空格,包括新行。