gpt4 book ai didi

php - 多行负向超前

转载 作者:行者123 更新时间:2023-12-03 18:41:13 25 4
gpt4 key购买 nike

我对regex不太满意(我花了几个小时),而且我很难替换2个标识符(“ {|”和“ |}”)之间的所有空行

我的正则表达式看起来像这样(对不起,您的眼睛):(\{\|)((?:(?!\|\}).)+)(?:\n\n)((?:(?!\|\}).)+)(\|\})


(\{\|):字符“ {|”
((?:(?!\|\}).)+):如果不是在“ |}”之后的所有内容(负向超前)
(?:\n\n):我要删除的空行
((?:(?!\|\}).)+):如果不是在“ |}”之后的所有内容(负向超前)
(\|\}):字符“ |}”


Demo

它可以工作,但是只删除最后一个空行,您能帮助我使它与所有空行一起工作吗?

我尝试在\ n \ n上添加一个否定的前瞻性,并在所有内容上重复一个组,但没有成功。

最佳答案

几种方法:

基于\G的模式:(仅需要一个模式)

$txt = preg_replace('~ (?: \G (?!\A) | \Q{|\E ) [^|\n]*+ (?s: (?! \Q|}\E | \n\n) . [^|\n]*)*+ \n \K \n+ ~x', '', $txt);


\G匹配字符串的开头或最后一次成功匹配之后字符串中的位置。这样可以确保多个匹配是连续的。

我所说的基于 \G的模式可以像这样被模式化:

(?: \G position after a successful match | first match beginning ) reach the target \K target


“到达目标”部分设计为永远不会匹配结束序列 |}。因此,一旦找到最后一个目标, \G部分将失败,直到第一个匹配部分再次成功。

~ 
### The beginning
(?:
\G (?!\A) # contigous to a successful match
|
\Q{|\E # opening sequence
#; note that you can add `[^{]* (*SKIP)` before to quickly avoid
#; all failing positions

#; note that if you want to check that the opening sequence is followed by
#; a closing sequence (without an other opening sequence), you can do it
#; here using a lookahead
)

### lets reach the target
#; note that all this part can also be written like that `(?s:(?!\|}|\n\n).)*`
#; or `(?s:[^|\n]|(?!\|}|\n\n).)*`, but I choosed the unrolled pattern that is
#; more efficient.

[^|\n]*+ # all that isn't a pipe or a newline

# eventually a character that isn't the start of |} or \n\n
(?s:
(?! \Q|}\E | \n\n ) # negative lookahead
. # the character
[^|\n]*
)*+
#; adding a `(*SKIP)` here can also be usefull if there's no more empty lines
#; until the closing sequence

### The target

\n \K \n+ # the \K is a conveniant way to define the start of the returned match
# result, this way, only \n+ is replaced (with nothing)
~x




preg_replace_callback :(更简单)

$txt = preg_replace_callback('~\Q{|\E .*? \Q|}\E~sx', function ($m) {
return preg_replace('~\n+~', "\n", $m[0]);
}, $txt);


demos

关于php - 多行负向超前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56994824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com