正则表达式替换美元符号之间的空格
regex replace spaces between dollar signs
如何替换两个美元符号之间的空格?
使用这个正则表达式一切正常,我可以删除 R 和 R 之间的空格。
\s(?![^\R]*(\R|$))
the result
但是当我使用美元符号代替 R 时,它不起作用。也许美元符号有一些特殊的方法。
\s(?![^$]*($|$))
result with dollar sign
编辑:编程语言:PHP
其中一条评论中建议的 \s+(?!(?:(?:[^$]*$){2})*[^$]*$)
模式涉及大量回溯,但效率极低,甚至可能导致程序冻结。
这是我在 PHP 中的做法(用连字符替换 $
符号之间的 space):
$re = '~$[^$]+$~';
$str = "$ words words $ $ words words $ $ words words $ $ words words $";
$result = preg_replace_callback($re, function($m) {
return str_replace(" ", "-", $m[0]);
}, $str);
echo $result;
使用 $[^$]+$
模式,我们匹配两个美元符号之间的整个子字符串,在 preg_replace_callback
内,我们可以通过将 str_replace
应用于所有匹配来进一步操作替换.
如何替换两个美元符号之间的空格?
使用这个正则表达式一切正常,我可以删除 R 和 R 之间的空格。
\s(?![^\R]*(\R|$)) the result
但是当我使用美元符号代替 R 时,它不起作用。也许美元符号有一些特殊的方法。
\s(?![^$]*($|$)) result with dollar sign
编辑:编程语言:PHP
其中一条评论中建议的 \s+(?!(?:(?:[^$]*$){2})*[^$]*$)
模式涉及大量回溯,但效率极低,甚至可能导致程序冻结。
这是我在 PHP 中的做法(用连字符替换 $
符号之间的 space):
$re = '~$[^$]+$~';
$str = "$ words words $ $ words words $ $ words words $ $ words words $";
$result = preg_replace_callback($re, function($m) {
return str_replace(" ", "-", $m[0]);
}, $str);
echo $result;
使用 $[^$]+$
模式,我们匹配两个美元符号之间的整个子字符串,在 preg_replace_callback
内,我们可以通过将 str_replace
应用于所有匹配来进一步操作替换.