[英]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.