[英]regex: match everything until a new lines comes without space after it
我有这个例子:
This is a simple test text.
Yet another line.
START: This is the part that
needs match.
This part does not need
capture.
Wherever else text.
我想匹配这部分:
START: This is the part that
needs capture.
重点是我知道START:
在那里,它以一条新行结束,除了后面还有一个空格。
我从以下START: (.*?)
尝试了很多组合: START: (.*?)
我已经用\\ r \\ n和我能想到的任何东西进行格子化,只有它没有空格才能匹配。
我不是一个菜鸟,因为我很懒。 我问了几个小时。
这个怎么样:
preg_match(
'/^ # Start of line
START:\ # Match "START: "
.* # Match any characters except newline
\r?\n # Match newline
(?: # Try to match...
^ # from the start of the line:
\ + # - one or more spaces
.* # - any characters except newline
\r?\n # - newline
)* # Repeat as needed/mx',
$subject)
这假设所有行都是换行符。
此代码将与您的示例测试一起正常运行。
解决方法是在preg_match之前替换新行的标记(在!之后恢复!)和正则表达式结束时的Ungreedy修饰符(U)
<?php
$token = '#####';
$text = <<<TXT
This is a simple test text.
Yet another line.
START: This is the part that
needs match.
This part does not need
capture.
Wherever else text.
TXT;
$text = str_replace("\n", $token, $text);
if (preg_match('/(?P<match>START:(.)*)(' . $token . '){1}[^ ]+/Uu', $text, $matches))
{
$match = str_replace($token, "\n", $matches['match']);
var_dump($match);
}
$text = str_replace($token, "\n", $text);
输出将是:
string(42) "START: This is the part that
needs match."
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.