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 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制