gpt4 book ai didi

php - 如何解决 PHP lookbehind 固定宽度限制?

转载 作者:可可西里 更新时间:2023-11-01 12:53:22 24 4
gpt4 key购买 nike

我在尝试匹配页面上特定单词之间的所有数字时遇到了问题。你将如何匹配以下文本中的所有数字,但只匹配单词“begin”和“end”之间的数字?

11
a
b
13
begin
t
899
y
50
f
end
91
h

这个有效:

preg_match("/begin(.*?)end/s", $text, $out);
preg_match_all("/[0-9]{1,}/", $out[1], $result);

但是可以用一个表达式来完成吗?

我试过了,但没用

preg_match_all("/begin.*([0-9]{1,}).*end/s", $text, $out);

最佳答案

您可以像这样使用 \G anchor ,并进行一些前瞻以确保您不会“越界”(超出两个词之间的区域):

(?:begin|(?!^)\G)(?:(?=(?:(?!begin).)*end)\D)*?(\d+)

regex101 demo

(?:                  # Begin of first non-capture group
begin # Match 'begin'
| # Or
(?!^)\G # Start the match from the previous end of match
) # End of first non-capture group
(?: # Second non-capture group
(?= # Positive lookahead
(?:(?!begin).)* # Negative lookahead to prevent running into another 'begin'
end # And make sure that there's an 'end' ahead
) # End positive lookahead
\D # Match non-digits
)*? # Second non-capture group repeated many times, lazily
(\d+) # Capture digits

一个调试表达式,如果这也有帮助的话:

Regular expression visualization

关于php - 如何解决 PHP lookbehind 固定宽度限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22195365/

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