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条)

报告相同问题?

悬赏问题

  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化