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

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

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 { { {.

图片转代码服务由CSDN问答提供 功能建议

对于那些正则表达式专家,你能帮我调整这个正则表达式,总是在两个匹配的字符之间添加一个空格。

我的尝试是解决Vue.js对于从服务器端传递的数据的插值安全问题(Vue.js将尝试评估两个花括号之间的任何内容)。 目标是:

  1. 要始终确保两个花括号之间的空格
  2. 不要在不必要的地方添加额外的空格。

    我的str_replace解决方案(仅实现目标#1)

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

    我到目前为止尝试的正则表达式:

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

    因此它会检查任何未跟随的匹配字符 空格并在两个字符之间插入空格。

    正则表达式在大多数情况下有效,但在有三个或更多匹配字符时失败。

    Ex : {{{返回 {{{,但预期输出为 {{{

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drox90250557
    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.

    点赞 评论

相关推荐