我正在尝试编写一个正则表达式来转义未被{}包围的$符号。
这是我到目前为止所做的:\^\$|[^\{]\$\
$test
预期:匹配实际:匹配
{$test1}
预期:不匹配实际:不匹配
{$test} $test1
预期:匹配第二个实际:匹配第二个$符号前的空格
{ $test3 }
预期:不匹配实际:匹配$ sign之前的空格
所以基本上如果$括在括号中,它应该永远不匹配,但任何其他$应匹配。
我正在使用php,我假设没有括号嵌套。括号和$符号之间可以有空格(n个空格或换行符或制表符,任何类型的空格)。
答案 0 :(得分:3)
这应该适用于假定没有嵌套括号的
$result = preg_replace('/\$(?![^{]*\})/m', '', $subject);
解释
"
\$ # Match the character “$” literally
(?! # Assert that it is impossible to match the regex below starting at this position (negative lookahead)
[^{] # Match any character that is NOT a “{”
* # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
} # Match the character “}” literally
)
"
答案 1 :(得分:0)
怎么样:\^(?:{[^}]*}|[^{])*\$\
$1\\$