[英]Regex starting with a zero length line and continuing across lines in Java
我想匹配以下內容:零長度的行,匹配持續跨非零長度的行,直到在一行中匹配特定的字符串為止。 例如:比賽從零長度線開始,一直持續到到達STOP:
Some random text I don't care about
The match starts at the beginning of this line
The match continues across this line
The match stops here STOP more
text I don't care about
有什么建議么?
謝謝
應該這樣做:
(?ms)^[ \t]*+$\s*+((?:(?!STOP).)*+)
一些演示:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String text = "Some random text I don't care about" + "\n" +
"" + "\n" +
"The match starts at the beginning of this line" + "\n" +
"The match continues across this line" + "\n" +
"The match stops here STOP more" + "\n" +
"don't care about" + "\n" +
"" + "\n" +
"" + "\n" +
"" + "\n" +
"foo" + "\n" +
"barSTOP" + "\n" +
"text I don't care about";
Matcher m = Pattern.compile("(?ms)^[ \t]*+$\\s*+(?:(?!STOP).)*+").matcher(text);
while(m.find()) {
System.out.println("match ->"+m.group()+"<-");
}
}
}
將輸出:
match ->
The match starts at the beginning of this line
The match continues across this line
The match stops here <-
match ->
foo
bar<-
一個小解釋:
(?ms) # enable mutli-line and dot-all
^[ \t]*+$ # match and empty line
\s*+ # match the line break
( # start group 1
(?:(?!STOP).) # if the string 'STOP' cannot be seen, match any character
*+ # match the previous zero or more times (possessively)
) # stop group 1
確保設置“匹配多行”標志,表達式為"\\\\n(\\\\n.*STOP)"
。 第一個(也是唯一一個)匹配組產生您的結果。 在DOS和Windows系統上,使用"\\\\r\\\\n"
代替"\\\\n"
。
(?ms)^$(.+)STOP
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.