在正则表达式的行前删除

Delete before a line with regex

我在 PHP 中使用 preg_replace 删除子字符串前的文本,如

unnecessary stuff
unnecessary stuff
DELETE ME and some more stuff
This line should be the beginning
the rest.

/^.{0,1000}DELETE ME/is

如何删除整行 DELETE ME

我用.{0,1000}限制删除

您可以使用此正则表达式来匹配:

/^.{0,1000}DELETE ME[^\r\n]*\R/is

RegEx Demo

详情:

  • [^\r\n]*:匹配0个或多个除\r\n
  • 以外的任意字符
  • \R:匹配任意unicode行尾字符

您可以使用内联修饰符来控制 . 匹配的内容:

'~(?s)^.{0,1000}DELETE ME(?-s).*\R?~i'
  ^^^^                   ^^^^^

regex demo

(?s) 内联 DOTALL 修饰符将使字符 类 之外的所有 . 匹配任何字符,包括所有换行字符,并且 (?-s) 将关闭此 DOTALL模式,并且模式中它右侧的所有 . 将停止匹配换行符。

more details from rexegg.com:

Inline Modifier (?s)
In .NET, PCRE (C, PHP, R…), Perl, Python and Java (but not Ruby), you can use the inline modifier (?s), for instance in (?s)BEGIN .*? END. See the section on inline modifiers for juicy details about three additional features (unavailable in Python): turning it on in mid-string, turning it off with (?-s), or applying it only to the content of a non-capture group with (?s:foo).

then

✽ Except in Ruby, (?s) activates "single-line mode", a.k.a. DOTALL modes, allowing the dot to match line break characters. In Ruby, the same function is served by (?m)

此外,如果 DELETE ME 出现在字符串的最后一行,因为 \R? 匹配 1 或 0 个换行符,则使用 \R? 您还将匹配整个字符串的末尾.