简体   繁体   English

匹配多行以某些字符开头和结尾的文本

[英]Matching text on multiple lines which begins and ends with some characters

i have a source file something like 我有一个类似的源文件

String some_words_come_here{
    //some string lines
    //some string lines
    //some string lines
    //some string lines
};

I am using it in java 我在Java中使用它

Pattern.compile("(?m)^Strin.+\\};$", Pattern.MULTILINE | Pattern.DOTALL); 

but this does not work well 但这不能很好地工作

with

Pattern.compile("(?m)^Strin.+", Pattern.MULTILINE); 

i get the string just until the end of the line. 我得到的字符串一直到行尾。 because .+ is quitting at the end of the line. 因为.+在行尾退出。

Pattern.compile("^String[^}]+\\};$", Pattern.MULTILINE);

should work unless there are } somewhere inside those lines (and unless there is whitespace before String or after }; ). 除非这些行内有} (并且除非在String之前或};之后有空格),否则它应该起作用。

Explanation: 说明:

^String starts the match at the beginning of the line; ^String在行的开头开始匹配; match String literally. 从字面上匹配String

[^}]+ matches one or more occurrences of any character except } . [^}]+匹配除}之外的任何一个或多个字符。

\\\\};$ matches }; \\\\};$匹配}; and end-of-line. 和行尾。 The backslash escapes the } , and since the backslash itself needs to be escaped in a Java string, too, you need two of them. 反斜杠转义} ,并且由于反斜杠本身也需要在Java字符串中转义,因此您需要两个反斜杠。

^String .*{\r*[^.*$]*};$

this works with Kodos tool. 这适用于Kodos工具。

a test in Java : Java测试:

package mytest;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

    public class Test4 {

     /**
      * @param args
      */
     public static void main(String[] args) {

      StringBuffer sb = new StringBuffer();
      sb.append("String some_words_come_here{").append("\n")
       .append("    //some string lines\n")
       .append("    //some string lines\n")
       .append("    //some string lines\n")
       .append("};\n");
      String regex = "^String .*\\{\\r*[^.*$]*\\};$";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(sb.toString());
      System.out.println(m.find());
      System.out.println(m.group(0));

     }

    }

output: 输出:

true
String some_words_come_here{
    //some string lines
    //some string lines
    //some string lines
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM