正则表达式替换转义字符

时间:2016-01-26 17:50:24

标签: regex

我想定义一个正则表达式模式,用相应的值替换转义字符。 例如字符串

  

XY \ TZ \\ X

应转换为

  

XY {标签}Ž\ X

问题是如何处理

之类的事情
  

XY \\\\\吨

这个字符串应该成为

  

XY \\ {标签}

我不知道如何创建一个只匹配奇数反斜杠的模式。

1 个答案:

答案 0 :(得分:0)

This isn't something that can be accomplished using a single pattern. To start, strip out collections of backslashes:

s/\\\\/\\/g

This replaces two backslashes with a single one.

Then you can just apply one pattern per escaped character: s/\\t/\t/g

The trick here is to escape the backslash you want to replace. What this'll do is replace the literal string "\t" with a tab character.