2

I'm trying to split string name\|dial_num|032\|0095\\|\\0099|\9925 by delimiter | but it will skip \|. I have found solution in this link: Javascript regexp that matches '.' not preceded by '\' (lookbehind alternative) but it skips \\| too.

The right result must be: [name\|dial_num,032\|0095\\,\\0099,\9925].

The rule is in case \\\| or \\\\\| or etc, | is still a valid delimiter but in case \\\\| or even more, it isn't.

Any help will be appreciate .

4

2 回答 2

2

通常的解决方法是使用match而不是split

> s = "name\\|dial_num|032\\|0095\\\\|\\\\0099|\\9925"
"name\|dial_num|032\|0095\\|\\0099|\9925"
> s.match(/(\\.|[^|])+/g)
["name\|dial_num", "032\|0095\\", "\\0099", "\9925"]

附带说明一下,即使 JS 确实支持后视,它也不是一个解决方案,因为(?<!\\)|也会错误地跳过\\|.

于 2013-10-04T08:13:45.970 回答
0

我挑战自己使用替换字符串方法..

我使用regex101.com(PCRE、Javascript 和 Python 正则表达式引擎的流行在线测试器)得到了正确的结果

// input : name\|dial_num|032\|0095\\|\\0099|\9925
// regex : ([^\\|](?:\\\\)*)\|                       with global flag
// replacement : $1,
// output: name\|dial_num,032\|0095\\,\\0099,\9925   <= seams okey right !?

测试 ..

var str = 'name\\|dial_num|032\\|0095\\\\|\\\\0099|\\9925';
str = str.replace(/([^\\|](?:\\\\)*)\|/g,'$1,');
console.log(str);
// > name\|dial_num,032\|0095\\,\\0099,\9925
于 2013-10-04T13:48:42.757 回答