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

Kri*_*eth 7 php regex

我试图匹配在我的页面上的特定单词之间找到的所有数字时遇到了问题.您将如何匹配以下文本中的所有数字,但只能在"开始"和"结束"之间进行匹配?

11
a
b
13
begin
t
899
y
50
f
end
91
h
Run Code Online (Sandbox Code Playgroud)

这有效:

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

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

我尝试了这个,但它没有做到这一点

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

Jer*_*rry 7

您可以\G像这样使用锚点,以及一些预测,以确保您不会"超出领域"(在两个单词之间的区域之外):

(?:begin|(?!^)\G)(?:(?=(?:(?!begin).)*end)\D)*?(\d+)
Run Code Online (Sandbox Code Playgroud)

regex101演示

(?:                  # 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
Run Code Online (Sandbox Code Playgroud)

一个debuggex,如果这也有帮助:

正则表达式可视化