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
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 };
).
Explanation:
^String
starts the match at the beginning of the line; match String
literally.
[^}]+
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.
^String .*{\r*[^.*$]*};$
this works with Kodos tool.
a test in 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
};
精彩评论