doushou8299 2014-05-23 08:30
浏览 194
已采纳

正则表达式正好用2替换2个反斜杠

I have a string where 2 backslashes must become 3 backslashes. With all the escaping of backslashes, I can't do it and nothing's working.

For example:

  • aaaaa\\aaaaa must become aaaaa\\\aaaaa
  • aaaaa\\\aaaaa STAYS aaaaa\\\aaaaa (2 backslashes in a row must not be detected)

I managed this, which works in regex101.com:

(\\\\)([^\\])

so in php, it would be:

preg_replace('/(\\\\)([^\\])/', '\\\$2', $bob);

But php gives me this error message:

preg_replace(): Compilation failed: missing terminating ] for character class at offset 10

So I don't know if it's a bug of PHP, but I need another way of doing this and I can't find the solution on google.

  • 写回答

2条回答

  • dousha1394 2014-05-23 08:39
    关注

    Try this regex:

    (?<!\x5C)\x5C{2}(?!\x5C)
    

    Backslashes can be a real nightmare here. It's better to use the ASCII code of the backslash right into the regex.

    Sample code:

    define('THREE_SLASHES', preg_quote('\\\\\\'));
    define('RE_TWO_SLASHES_ONLY', '~(?<!\x5c)\x5c{2}(?!\x5c)~');
    
    $test='aaaaa\\\\aaaaa';
    echo preg_replace(RE_TWO_SLASHES_ONLY, THREE_SLASHES, $test) . '<br>';
    
    $test='aaaaa\\\\\\aaaaa';
    echo preg_replace(RE_TWO_SLASHES_ONLY, THREE_SLASHES, $test) . '<br>';
    

    Output

    aaaaa\\\aaaaa
    aaaaa\\\aaaaa
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?