Regex 如何通过正则表达式选择包含字符串的文本块?

Regex 如何通过正则表达式选择包含字符串的文本块?,regex,Regex,鉴于以下案文: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus id tristique est. Mauris eget massa leo. Pellentesque egestas ante vitae finibus luctus. Nam tristique metus nec semper semper. 是否可以通过正则表达式匹配包含字符串tristique的两个块 这是两个匹

鉴于以下案文:

Lorem ipsum dolor 
sit amet, consectetur 
adipiscing elit.

Phasellus id 
tristique est.

Mauris eget massa leo.
Pellentesque egestas 
ante vitae finibus luctus. 

Nam tristique metus 
nec semper semper.
是否可以通过正则表达式匹配包含字符串
tristique
的两个块

这是两个匹配项:

Phasellus id 
tristique est.

Nam tristique metus 
nec semper semper.

你可以试试下面的正则表达式

(?s)\b(?:(?!\n\n).)*?\btristique\b(?:(?!\n\n).)*


(?:(?!\n\n)。*
匹配任何字符,但不匹配
\n\n
,零次或多次。

合理的方法是将字符串按段落(
\n\n+
)拆分,然后查找带有“三字型”的段落。这可能是最快的方法

Javascript示例:

var result = text.split(/^\n+|\n\n+/).filter(function (elt) {
    return /\btristique\b/.test(elt);
});
要一次性完成相同的任务,并防止大量回溯,您需要使用javascript中不可用的高级正则表达式功能。PHP的一个示例:

$pattern = <<<'EOD'
~^
# non-empty lines without the target word
(?:
    (?=\N) #check if there is one character
    # content without the target word
    [^t\n]*+ #all until a "t" or a newline
    (?: \Bt+[^t\n]* | t+(?!ristique\b)[^t\n]* )*+ #when a "t" is met
    \n #a newline
)*+

# characters until the target word
[^t\n]*+
(?: \Bt+[^t\n]* | t+(?!ristique\b)[^t\n]* )*+
(*SKIP) # if the target word doesn't follow then skip the substring

tristique  # target: note that word boundaries are implicit
\N*        # trailing characters
(?:\n\N+)* # following non empty lines
~mx
EOD;

if (preg_match_all($pattern, $text, $matches)) {
// do what you have to do
}

$pattern=您使用什么语言?