php - 如何破译正则表达式?
问题描述
preg_match_all('/({\$([^}]+)})/', $result, $matches)
有人可以帮助破译此调用中的正则表达式吗?
正则表达式不是我最好的。据我所知,它正在寻找看起来像{$foo}
但我想我错过了什么的比赛?
解决方案
在这里,我们有一个相当简单的表达式,它传递了几乎所有的字符,从左边界用{
和$
从右边界用}
。它收集了介于两者之间的几乎所有字符:
演示
正则表达式
如果不需要此表达式,可以在regex101.com中对其进行修改或更改。例如,如果我们愿意,我们可以限制它并使特殊字符失效:
({\$\w+})
演示
正则表达式电路
jex.im可视化正则表达式:
演示
const regex = /({\$\w+})/gm;
const str = `{\$foo}
{\$foo_090_}
{\$foo_@#\$%_5678}
{\$foo_@#\$%_{+[]:}`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
PHP 测试
$re = '/({\$\w+})/m';
$str = '{$foo}
{$foo_090_}
{$foo_@#$%_5678}
{$foo_@#$%_{+[]:}';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
推荐阅读
- python - 张量流错误(tensorflow.python.framework.errors_impl.InternalError)
- graph - 如何为图的每个节点打印 MST 树?
- c# - XML 反序列化代码在控制台应用程序中有效,但在 Xamarin.Forms 中引发 NullReferenceException
- android - 如果我在Android中使用协程读/写Realm以避免阻塞UI,是否还需要使用后台线程?
- c - 存储变量的地址
- ios - “无法解析主机“<在此处插入 URL>”没有与主机名关联的地址”
- python - 使用 Python 和 Beautiful Soup 抓取 Google 新闻结果只检索没有标题的第一页
- python - 如何取消函数中的事件
- c++ - 用于筛子的最佳数据结构是什么(即一些被划掉的数字列表)?
- bash - 获取自定义 bash 脚本的可接受方式是什么?