Java RegEx - Regular expression to split a paragraph with start and end

后端 未结 3 2020
-上瘾入骨i
-上瘾入骨i 2021-01-15 05:10

I am new to java regex.Please help me. Consider the below paragraph,

Paragraph :

            Name abc
            sadghsagh
            hsajdjah N         


        
3条回答
  •  执念已碎
    2021-01-15 05:59

    String s = "Name abc sadghsagh hsajdjah !!! Name ggg dfdfddfdf !!! Name hhhh sahdgashdg asjdhjasdh sadasldkalskd asdjhakjsdhja !!!!! ";
    String startsWith = "Name";
    String endsWith = "!!!";
    
    // non-greedily get all groups starting with Name and ending with !!!
    String pattern = String.format("(%s).*?(%s)", Pattern.quote(startsWith), Pattern.quote(endsWith));
    System.out.println(pattern);
    
    Matcher m = Pattern.compile(pattern, Pattern.DOTALL).matcher(s);
    while (m.find()) 
      System.out.println(m.group());
    

    output:

    (\QName\E).*?(\Q!!!\E)
    Name abc sadghsagh hsajdjah !!!
    Name ggg dfdfddfdf !!!
    Name hhhh sahdgashdg asjdhjasdh sadasldkalskd asdjhakjsdhja !!!
    

提交回复
热议问题