如何找到所有匹配项,而不是最后一场比赛,然后在preg_match_all()中查看后面

发布于 2025-01-24 19:26:34 字数 415 浏览 0 评论 0原文

我有这个文字。

*s*
*q: what is 3+3? *.
*o: 3 *.
*o: 4 *.
*o: 6 *.
*e*

*s*
*q: what is 4*4? *.
*o: 7 *.
*o: 12 *.
*o: 16 *.
*e*

*s*
*q: what is 10/2? *.
*o: 1 *.
*o: 5 *.
*e*

)中写下了以下表达

preg_match_all("/(?<=\*s\*)[\s\S\d\D\w\W](?=\*e\*e)/", $str, $matches);

我在php preg_match_all ( *S**E*。 如何获得重复集。我想要此正则三盘。

I have this text.

*s*
*q: what is 3+3? *.
*o: 3 *.
*o: 4 *.
*o: 6 *.
*e*

*s*
*q: what is 4*4? *.
*o: 7 *.
*o: 12 *.
*o: 16 *.
*e*

*s*
*q: what is 10/2? *.
*o: 1 *.
*o: 5 *.
*e*

I wrote the following expression in php preg_match_all()

preg_match_all("/(?<=\*s\*)[\s\S\d\D\w\W](?=\*e\*e)/", $str, $matches);

But the regex matches from first *s* to the last *e* and skips the middle *s* and *e*.
how can I get the repeating sets. I want three sets from this regex.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

木有鱼丸 2025-01-31 19:26:34

您的代码不会像您描述的那样行事,因此我从修改后的正则正则(由于文书复制错误而丢失了?)

preg_match_all("/(?<=\*s\*)[\s\S\d\D\w\W]+(?=\*e\*)/", $str, $matches);

您的正则是您的正则是贪婪的,即。试图在输入中找到与模式匹配的最长字符串。正如您观察到的那样,这将是整个内容。

为了获得所需的结果,请在模式和使用中更具体:

/(?<=\*s\*[\r\n])(\*.*\*\.[\r\n]+)+/

lookBehind现在是指*s*启动包括newline字符的块。表达式的其余部分表示以*开始,并以*。*。结尾。 THSI行为在。*模式不是匹配线终止字符上,这是默认

情况下,在匹配包含*e*e*e*,因为它不会以字符结尾。

另请注意,您可能必须修改文件的newline字符(序列)中的lookBehind部分。

不需要落后的部分。

使用在REGEX 101上的示例检查匹配。

Your code would not behave as you describe, so I start off with the modified regex (differences lost due to clerical copy error ?)

preg_match_all("/(?<=\*s\*)[\s\S\d\D\w\W]+(?=\*e\*)/", $str, $matches);

Your regex is matching greedily, ie. tries to find the longest string in your input that matches the pattern. As you observed, this would be the entire content.

In order to get the desired result, be more specific in your pattern and use:

/(?<=\*s\*[\r\n])(\*.*\*\.[\r\n]+)+/

The Lookbehind now refers to the *s* initiating a block including the newline character. The remainder of the expression denotes an arbitrary number of consecutive lines starting with a * and ending with *.. Thsi behavior hinges on the .* pattern not matching line termination characters, which is the default

Note that this cuts off before matching a line containing *e* as it does not end with the . character.

Also note that you might have to modify the lookbehind portion filling in the newline character (sequence) of your file.

No trailing lookahead portion is needed.

Check the matching with this example on Regex 101.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文