需求:(为方便表达,下面引号内字符串本身不作转义,即"\\"代表的就是两个斜杠)
对于一系列的("abc", "xyz"),"\abc"是"xyz"的转义,要实现“\abc” -> "xyz"而"\\abc" -> "\abc"的变换。
0. Google it
Google给我提供了一堆正则表达式应当如何转义的资料
1. Attempt Round 0
replace("\abc", "xyz"); replace("\\", "\");
这使得"\\abc" -> "\xyz",失败
2. Attempt Round 1
replace(/(?<!\\)((\\*)\2)\\abc/g, "$1xyz"); replace("\\", "\");
什么?JavaScript不支持"(?<!)"?
3. Attempt Round 2
replace("(?:[^\\]|^)((\\*)\2)\\abc"/mg, "$1xyz"); replace("\\", "\");
看上去不错。仔细一看转义内容前面的那个字被吃掉了,~~(>_<)~~
4. 上v2ex提问
进行中……
对于一系列的("abc", "xyz"),"\abc"是"xyz"的转义,要实现“\abc” -> "xyz"而"\\abc" -> "\abc"的变换。
0. Google it
Google给我提供了一堆正则表达式应当如何转义的资料
1. Attempt Round 0
replace("\abc", "xyz"); replace("\\", "\");
这使得"\\abc" -> "\xyz",失败
2. Attempt Round 1
replace(/(?<!\\)((\\*)\2)\\abc/g, "$1xyz"); replace("\\", "\");
什么?JavaScript不支持"(?<!)"?
3. Attempt Round 2
replace("(?:[^\\]|^)((\\*)\2)\\abc"/mg, "$1xyz"); replace("\\", "\");
看上去不错。仔细一看转义内容前面的那个字被吃掉了,~~(>_<)~~
4. 上v2ex提问
进行中……