Question

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 .

Was it helpful?

Solution

the usual workaround is to use match instead of 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"]

As a side note, even if JS did support lookbehinds, it won't be a solution, because (?<!\\)| would also incorrectly skip \\|.

OTHER TIPS

I challenged myself to use replace String method..

I got the right result using regex101.com (a popular online tester for PCRE, Javascript and Python regular expressions engines)

// 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 !?

Test ..

var str = 'name\\|dial_num|032\\|0095\\\\|\\\\0099|\\9925';
str = str.replace(/([^\\|](?:\\\\)*)\|/g,'$1,');
console.log(str);
// > name\|dial_num,032\|0095\\,\\0099,\9925
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top