Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 多行模式的Regex可选匹配_Java_Regex - Fatal编程技术网

Java 多行模式的Regex可选匹配

Java 多行模式的Regex可选匹配,java,regex,Java,Regex,我正试图找出一个正则表达式,它支持以下两个用例: 用例1: -- File 1 (input) -- keepthis junkhere: this should be removed 用例2: -- File 2 (input) -- keepthis ------------ junkhere: this should be removed 基本上,我正在构建一个正则表达式来删除“junkhere:”和下面的所有内容。然而,在用例2中,在“junkhere:”之前的一行中有一个可选的

我正试图找出一个正则表达式,它支持以下两个用例:

用例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" 
Pattern JUNKHERE_REGEX=Pattern.compile(“^(((+)(*))?JUNKHERE:(*)”,Pattern.MULTILINE | Pattern.DOTALL);
Matcher m=JUNKHERE_REGEX.Matcher();
if(m.find())| |(n.find()| |(o.find()){//在这种情况下,这里可能有其他匹配符n和o,因此我希望保持replaceall代码在相同的下面,这样我就不必创建新的if语句
text=m.replaceAll(“”);
text=text.replaceAll(“[\n]+$”,“”);//替换并删除任何换行符
}
System.out.println(text);//应回显“keepthis”
我对正则表达式不是很在行,但是我需要什么才能使它在用例2(和用例1)中工作呢


谢谢!

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


在这里测试:在这里:


在Java中,必须使用两个转义字符:

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

你能用上面的代码做一个SSCE吗,它甚至不会编译。我假设你在regex模式后意外地丢失了一个双引号…你所给出的对usercase 2和usercase 1都有效。检查此链接再次感谢你的回复。你是如何创建很酷的regex图表的?看看debuggex.com