【问题标题】:Regex: Matching strings without breaking the match string by matching to a escaped quote in middle of the string正则表达式:通过匹配字符串中间的转义引号来匹配字符串而不破坏匹配字符串
【发布时间】:2010-12-11 09:22:44
【问题描述】:

我正在匹配模板 if 语句中的条件。问题在于在将条件语句分解为单独的条件之前解析字符串。

我在条件分解之前用占位符替换字符串条件,这样字符串就不会干扰分解模式匹配。

下面的代码可以正常工作。

// remove quoted strings from conditional elements as will conditional tokenising below
if (preg_match_all('/([\"\'])([^\\1]*?)\\1/s', $conditions, $string_matches))
{   
    $uid = uniqid(time().'_');
    $strings = array(
            'id' => $uid, 
            'matches' => array()
        ); 
    $replacements = array();
    foreach($string_matches[0] as $key=>$match)
    {
        $match_id = '#'.$uid.md5($match);
        $replacements[$match] = $match_id;
        $strings['matches'][$match_id] = array(
                'match' => $match,
                'content' => $string_matches[2][$key],
            );
    }
    $conditions = str_replace(array_keys($replacements), array_values($replacements), $conditions);
}

它匹配以下伟大的

boolean_arg1 && arg2 !== 'testing multi quotes' && arg3 === "test & yup" -or-
boolean_arg1 && arg2 !== 'testing "multi" quotes' && arg3 === "test & yup"

给我

boolean_arg1 && arg2 !== #1292059008_4d0341809c0f74062e5ac5086fb24f8e8383a137a5a5e && arg3 === #1292059008_4d0341809c0f7d4820850f1f6e06677e741be556352e3
boolean_arg1 && arg2 !== #1292059102_4d0341de3f5196213c34e77a2cfbb11f867f9ed57c85f && arg3 === #1292059102_4d0341de3f519d4820850f1f6e06677e741be556352e3

但是在字符串中引入转义引号会破坏转义字符串的模式匹配。

boolean_arg1 && arg2 !== 'testing "multi" \'quotes' && arg3 === "test && yup"

给予

boolean_arg1 && arg2 !== #1292059161_4d03421974c3166a7cae87ddc1002905892eff6453bd4quotes' && arg3 === #1292059161_4d03421974c31d4820850f1f6e06677e741be556352e3

(注意引号')在第一次替换之后。

我不太擅长查找等。我想知道是否有一个简单的解决方案可以将上面代码中的正则表达式转换为匹配带有转义引号的完整字符串?

【问题讨论】:

    标签: php regex templates


    【解决方案1】:

    使用反映转义序列的模式,例如:

    /"(?:[^"\\]*|\\["\\])*"|'(?:[^'\\]*|\\['\\])*'/
    

    只有 \\\"\' 的转义序列是已知的。您可以通过更改 ["\\]/['\\] 来扩展它们。

    【讨论】:

    • 那个正则表达式会引发编译错误?我虽然是 ?:[ 但逃脱了它不起作用。不知道为什么。
    • @buggedcom:确保正确转义字符串中的\‍ 和引号。
    猜你喜欢
    • 1970-01-01
    • 2011-11-08
    • 2018-04-17
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 2018-07-26
    • 2014-10-08
    • 2023-03-13
    相关资源
    最近更新 更多