在使用正则表达式之前查找所有文本

时间:2010-06-18 16:24:22

标签: regex

如何使用正则表达式查找文本“包含此行之前的所有文字”之前的所有文字?

我在下面提供了一些示例文本,例如

This can include deleting, updating, or adding records to your database, which would then be reflex.

All text before this line will be included

You can make this a bit more sophisticated by encrypting the random number and then verifying that it is still a number when it is decrypted. Alternatively, you can pass a value and a key instead.

3 个答案:

答案 0 :(得分:12)

从解释开始...跳到结束以获得快速答案

要匹配特定的文本,并确认它在那里但不包括匹配,您可以使用正面的前瞻,使用符号(?=regex)

这确认了'正则表达式'存在于该位置,但只匹配起始位置,而不是它的内容。

所以,这给了我们表达式:

.*?(?=All text before this line will be included)

其中.是任何字符,而*?是一个懒惰匹配(与可能消耗尽可能多的金额的常规*相比,可能消耗的金额最少)。

但是,在几乎所有正则表达式中,.都会排除换行符,因此我们需要明确使用标志来包含换行符。 要使用的标志是s,(代表“单行模式”,虽然在某些风格中它也被称为“DOTALL”模式)。

这可以通过各种方式实施,包括......

在全球范围内,基于/的正则表达式:

/regex/s

内联,正则表达式的全局:

(?s)regex

内联,仅适用于括号内的部分:

(?s:reg)ex

作为一个函数参数(取决于你正在使用哪种语言进行正则表达式)

所以,你想要的正则表达式可能就是这样:

(?s).*?(?=All text before this line will be included)


然而,有一些警告:

首先,并非所有正则表达式都支持延迟量词 - 您可能只需使用.*,(或者如果“之前的所有文本...”可能出现多次,则可能会使用更复杂的逻辑,具体取决于精确的要求)

其次,并非所有正则表达式都支持前瞻,因此您需要使用捕获的组来获取要匹配的文本。

最后,您不能总是指定标记,例如上面的s,因此可能需要匹配“any或newline”(.|\n)或者[\s\S](空格而不是空格)空格)得到等价的匹配。

如果您受到所有这些限制(我认为XML实现是这样的),那么您将不得不这样做:

([\s\S]*)All text before this line will be included

然后从匹配结果中提取第一个子组。

答案 1 :(得分:9)

(.*?)All text before this line will be included

根据您正在使用的特定正则表达式框架,您可能需要包含一个标记,以指示.也可以匹配换行符。

第一个(也是唯一的)子组将包含匹配的文本。如何提取它将再次取决于您正在使用的语言和正则表达式框架。

如果您想包含“此行之前的所有文字...”文字,那么整个匹配就是您想要的。

答案 2 :(得分:1)

这应该这样做:

<?php
$str = "This can include deleting, updating, or adding records to your database, which would then be reflex.

All text before this line will be included

You can make this a bit more sophisticated by encrypting the random number and then verifying that it is still a number when it is decrypted. Alternatively, you can pass a value and a key instead.";

echo preg_filter("/(.*?)All text before this line will be included.*/s","\\1",$str);
?>

返回:

This can include deleting, updating, or adding records to your database, which would then be reflex.