匹配恰好有两个“=”的字符串两侧的字符
我需要一个 PHP 正则表达式来识别如下模式:
== 敏捷的棕色狐狸==
然而,正则表达式无法匹配:
=== 敏捷的棕色狐狸===
我构建了以下正则表达式 - 我非常接近:
={2}[a-zA-z0-9 ]*={2}
I need a PHP regex to identify patterns like:
== The Quick Brown Fox==
The regex cannot match, however:
=== The Quick Brown Fox===
I have the following regex constructed - I'm so close:
={2}[a-zA-z0-9 ]*={2}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用lookbehind before 和lookahead after,如下所示:
编辑: 虽然此解决方案有效,但它不如 Justin 的高效。
Use lookbehind before and lookahead after like so:
Edit: Although this solution works, it is not as efficient as Justin's.
这看起来像是 lookarounds 的工作:
我发现上面的内容是最易读的方式做这个。您还可以使用以下内容,其工作原理基本相同:
这还允许您在同一字符串中匹配多次,只要它们之间有一个分隔符(任何非
=
字符) 。例如,==foo== ==bar==
应产生 2 个匹配项,而==foo====bar==
应不产生任何匹配项。This looks like a job for lookarounds:
I find the above to be the most readable way to do this. You can also use the following, which works essentially the same way:
This will also allow you to match multiple times in the same string, as long as there's a break (any non-
=
character) between them. For example,==foo== ==bar==
should produce 2 matches, while==foo====bar==
should produce none.\s
匹配空格^
表示开始$
表示结束\s
matches white space^
denotes the begining$
denote the end