【问题标题】:Regex optional matching for multiline patterns多行模式的正则表达式可选匹配
【发布时间】:2013-11-30 00:42:03
【问题描述】:

我正在尝试找出一个支持以下 2 个用例的正则表达式:

用例 1:

-- File 1 (input) --
keepthis

junkhere:
this should be removed

用例 2:

-- File 2 (input) --
keepthis

------------
junkhere:
this should be removed

基本上,我正在构建一个正则表达式来删除“junkhere:”中的所有内容。但是,在用例 2 中有一个可选的“------------”,它有时会包含在“junkhere:”之前的行中,但并非总是如此(不确定 - 的确切含义) .

输出应该是:

-- File 3 (output) --
keepthis

我有以下正则表达式,它适用于用例 1,但不适用于用例 2:

Pattern JUNKHERE_REGEX = Pattern.compile("^(((-+)(.*))?junkhere:(.*))$", Pattern.MULTILINE | Pattern.DOTALL);

    Matcher m = JUNKHERE_REGEX.matcher(<input from either file1 or file2>);
    if (m.find()) || (n.find() || (o.find()) { // there could be other matchers here n and o in this case so I would like to keep the replaceall code below the same so I don't have to create a new if statement 
      text = m.replaceAll("");  
      text = text.replaceAll("[\n]+$", ""); // replace and delete any newlines
    }
    System.out.println(text); // should echo "keepthis" 

我对正则表达式不太擅长,但我需要什么才能使它适用于用例 2(和用例 1)?

谢谢!

【问题讨论】:

  • 你能不能用上面的代码做一个SSCCE,它甚至无法编译。
  • 我假设您在正则表达式模式后不小心遗漏了双引号...
  • 您提供的内容适用于用户案例 2 和 1.. 检查此链接 regexr.com?37eea

标签: java regex


【解决方案1】:

用空字符串替换[\n\r]+(?:[-]+[\n\r]+)?\s*junkhere:\s*[\n\r][\s\S]*的匹配项。


在这里测试:http://regexr.com?37edu 和这里:http://regexr.com?37ee1


在 Java 中,您必须使用双转义字符:

= text.replaceAll("[\\n\\r]+(?:[-]+[\\n\\r]+)?\\s*junkhere:\\s*[\\n\\r][\\s\\S]*", "");

【讨论】:

  • 再次感谢您的回复。你是如何创建很酷的正则表达式图表的?
  • 看看 debuggex.com
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多