首页 > 解决方案 > 如何破译正则表达式?

问题描述

preg_match_all('/({\$([^}]+)})/', $result, $matches)

有人可以帮助破译此调用中的正则表达式吗?

正则表达式不是我最好的。据我所知,它正在寻找看起来像{$foo}但我想我错过了什么的比赛?

标签: phpregexstringpreg-match-allregex-negation

解决方案


在这里,我们有一个相当简单的表达式,它传递了几乎所有的字符,从左边界用{$从右边界用}。它收集了介于两者之间的几乎所有字符:

在此处输入图像描述

演示

正则表达式

如果不需要此表达式,可以在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);

推荐阅读