在我想要实际匹配的内容之后停止正则表达式匹配*所有内容*!
我对整个正则表达式很陌生,并尝试在 PHP 中执行 preg_match_all
,这是我想要的结果,但问题是它匹配我实际的之后的所有内容想要...像这样:
字符串:这是一些东西
来自正则表达式的匹配:这里有一些代码
还有更多
想要来自正则表达式的匹配:此处的一些代码
还有更多这里有一些代码
这是我正在使用的正则表达式: /
(.*)<\/code>/
我认为它与开始和结束 /
分隔符有关,但我不完全确定。
任何帮助将不胜感激,谢谢!
I am quite new to the whole Regex thing and tried to do a preg_match_all
in PHP which, kind of the results I wanted but the problem is it matches everything after what I actually wanted... like so:
String: This is something <code>Some code here</code> and more
Match from Regex: <code>Some code here</code> and more
Wanted match from Regex: <code>Some code here</code>
Here is my regular expression that I'm using:/<code>(.*)<\/code>/
I think its something to do with the beginning and ending /
delimiters but I'm not entirely sure.
Any help would be appreciated, thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
星号是贪婪的,这意味着它将尽可能匹配。改用
它,让它变得懒惰。您还可以使用否定字符类:
编辑:由于 mvds 删除了他/她的答案,这里有一个提示:如果您不这样做,则可以避免转义斜杠 (
/
)不要像我上面那样使用它作为分隔符 ^ (使用!
)这是关于正则表达式的一个很好的资源:
http://www.regular-expressions.info/repeat.html
The star is greedy, meaning it will match as much as it can. Use
instead, making it lazy. You can also use negated character classes:
EDIT: Since mvds deleted his/her answer, here's a tip: You can avoid having to escape the slash (
/
) if you don't use it as a delimiter, like I did above ^ (used!
)Here's a good resource on regex:
http://www.regular-expressions.info/repeat.html
你想让
.*
变得非贪婪。如果您在模式的该部分之后放置?
,它将匹配正则表达式中匹配的下一部分之前的所有内容。因此,使正则表达式/
(.*?)<\/code>/
you want to make the
.*
be non greedy. If you put a?
after that part of the pattern it will match everything up to the next part of the regex that matches. So make the regex/<code>(.*?)<\/code>/
你需要禁用贪婪。我相信使用
.*?
代替。You need to disable greediness. Use
.*?
instead, I believe.我不是 100% 确定这是如何编译的 - 你需要这样转义第二个
/
:以便 PHP 将其识别为要匹配的字符而不是正则表达式的末尾(我认为它可能会作为替代正则表达式进行编译)。
I'm not 100% sure how this is even compiling - you need to escape the second
/
as so:So that PHP recognises it as a character to match rather than the end of the regular expression (I think it may be compiling as a substitute regex).