正则表达式所以反斜杠表示 'delete next char'

Regexp so backslash means 'delete next char'

我需要一个可以进行以下转换的正则表达式:

Input:  ab\xy
Output: aby


Input: ab\xy
Output: ab\xy

将所有这些反斜杠视为 LITERAL 反斜杠。即第一个输入的是字符序列['a', 'b', '\', 'x', 'y'],第二个是['a', 'b', '\', '\', 'x', 'y'].

规则是"in a string of characters, if a backslash is encountered, delete it and the following character ... unless the following character is a backslash, in which case delete only one of the two backslashes."

这是转义序列地狱,我似乎找不到出路。

您可以使用

(?s)\(\)|\.

并替换为 </code> 以在发现双反斜杠时恢复 <code>\

详情:

  • (?s) - 一个 dotall 修饰符,以便 . 可以匹配任何字符,包括换行符
    • \(\) - 匹配一个反斜杠,然后匹配另一个反斜杠并将其捕获到组 1
  • | - 或
  • \. - 匹配任何转义序列(反斜杠 + 任何字符)。

参见 regex demo and a PHP demo:

$re = '/\\(\\)|\\./s';
$str = 'ab\xy ab\\xy ab\\\xy';
echo $result = preg_replace($re, '', $str);
// => aby ab\xy ab\y