douduikai0562 2018-04-26 14:51
浏览 1126
已采纳

始终使用正则表达式在两个字符之间添加空格

For those regex experts out there, can you help me tweak this regex to always add a whitespace between two matching characters.

My attempt is to resolve the interpolation security issue with Vue.js for data passed from the server side (Vue.js will try to evaluate anything between two curly braces). The goal is:

  1. To always ensure whitespace between two curly braces
  2. Not add additional whitespace where unnecessary.

My str_replace solution (which accomplishes goal #1 only)

str_replace(
    ['{',  '}',  '{',  '}',  '{',  '}' ],
    ['{ ', '} ', '{ ', '} ', '{ ', '} '],
    $value
);

My attempted regex thus far:

preg_replace('/({|}|{|}|{|})(\S)/', '$1 $2', $value);

So it checks for any matching character that isn't followed by whitespace and inserts whitespace between the two characters.

The regex works in most cases, but fails when you have three or more matching characters.

Ex: {{{ returns { {{ but the expected output would be { { {.

  • 写回答

1条回答 默认 最新

  • drox90250557 2018-04-26 15:01
    关注

    It doesn't work as you expect it because the first two { characters match the regex, the replacement is made then the search continues with the 3rd character of the input string

    You can solve this by turning the second parenthesis into a forward assertion. This way, the second } is not consumed on the first match and the next search starts with the second character of the input string:

    preg_replace('/({|}|{|}|{|})(?=\S)/', '$1 ', $value);
    

    There is only one capture group this way, $2 is always empty and it is not needed any more in the replacement string.

    See it in action: https://3v4l.org/CaMHS. The +++ markers were added to show that the third { doesn't match the regex and no replacement occurs for it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Mapreduce是正常的,在运行其他jar包时并没有任何问题,只是在做LogCount.jar 时出的问题。如图所示
  • ¥15 ImportError: DLL load failed while importing _iterative: 找不到指定的模块。
  • ¥15 如何通过交互分析得出某高危患者对放疗获益更多
  • ¥15 相关性分析中,p<0.05, r=0.29,怎么评价相关性呢
  • ¥15 docker部署Mongodb后输入命令报错?
  • ¥15 将下列流程图转变成python程序代码
  • ¥15 我需要全国每个城市的最新小区名字等数据。
  • ¥15 开发一个小区生态的小程序
  • ¥15 如何解决Excel中dependent dropdown list 的问题
  • ¥15 MddBootstrapInitialize2失败