如何从给定字符串下面的\ n +到\ n以及\ n-到\ n范围内的java字符串中获取子字符串?

时间:2019-04-03 05:23:37

标签: java regex

输入字符串如下:

@@ -106,12 +106,12 @@ end loop\n loop map dummm56\n \tdummy data/path/u/u_op/kl-sc45\n end loop\n-\n-loop map {$df=56,$kl=20564300,$testId=\"jk: message1 message2:48667697\",$kl3=true,$kl=true, $kl=[2],$kl=$kl1, $kl1=true, $kl1=[1],$kl14=$kl15,$kl16=$kl14}\n+##### message2:48667697\n+loop map {val56}\n \tl1 l2/l3/i3/l7_l90/l90-SC21_l90/l90-l90_l90_l90\n end loop\n-\n-loop map {val56}\n+#####kl message45:48667697\n+loop map {val34}\n \ttestcases data/testcases/path1/[ath5+path6/UC20015-SC21/UC20015-SC21\n end loop\n

在上面的字符串中,我想获取所有从 \ n + \ n 结束的子字符串。另外,使用Java正则表达式从 \ n-开始,以 \ n 结尾。

预期输出如下:

blank  // here its blank as first \n- to next \n nothing is there.
loop map {$df=56,$kl=20564300,$testId=\"jk: message1 message2:48667697\",$kl3=true,$kl=true, $kl=[2],$kl=$kl1, $kl1=true, $kl1=[1],$kl14=$kl15,$kl16=$kl14} // as second \n- to next \n
##### message2:48667697 //third \n+ to next \n
loop map {val56}\n \tl1 l2/l3/i3/l7_l90/l90-SC21_l90/l90-l90_l90_l90 //fourth \n+ to next \n
blank // \n- to next \n
loop map {val56} // \n- to next \n
#####kl message45:48667697 // as \n+ to \n
loop map {val34} // as \n+ to \n

实际上,我想制作两个不同的集合,一个用于\ n +到\ n,另一个用于\ n-到\ n。我想将其用于以后的目的。

下面是我尝试过的Java代码:

String str="Pasted above string making sure no additional string literals should come.";
Pattern p0 = Pattern.compile("^(\\\\n[+|-])(.*?)(\\\\n.*)?$"); 
Matcher m = p0.matcher(str);
while (m.find()) {
System.out.printf( m.group(0));// here I am expecting my output to get printed.
}

有人可以帮我吗?任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

这可能会帮助您的正则表达式

^(\\\\n[+|-])(.*)$

^ - Start of line

\\\\n - escaping \

^(\\\\n[+|-]) - Starting point of line followed by \n with either + or -

(.*?) anything can follow after that (? for non-greedy search if \n follows after that)

(\\\\n.*)? - Might be that \n follows (4th line in text)

$ - End of line. Assuming that after end of line what follows is \n-new line

从您提供的输出中,您似乎还忘记了其他条件,例如为什么###problem statement1不在输出中,因为它以\n+开头并以新行结尾。下面是相同的代码段

 public static void main(String[] args) throws Exception {
    Pattern pattern = Pattern.compile("^(\\\\n[+|-])(.*?)(\\\\n.*)?$"); 
    Matcher matcher = null;

    BufferedReader br = new BufferedReader(new FileReader(
            "filePath"));
    String line = null;
    while ((line = br.readLine()) != null) {
        matcher = pattern.matcher(line);
        while (matcher.find()) {
            System.out.println(matcher.group(2));
        }
    }
}