【问题标题】:How to decipher a regular expression? [duplicate]如何破译正则表达式? [复制]
【发布时间】:2019-05-23 14:40:00
【问题描述】:
preg_match_all('/({\$([^}]+)})/', $result, $matches)

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

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

【问题讨论】:

标签: php regex string preg-match-all regex-negation


【解决方案1】:

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

DEMO

正则表达式

如果不需要此表达式,可以在 regex101.com 中修改或更改它。例如,如果我们愿意,我们可以限制它并使特殊字符失效:

({\$\w+})

DEMO

正则表达式电路

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);

【讨论】:

    猜你喜欢
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 2022-11-25
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 2011-10-30
    相关资源
    最近更新 更多