Search code examples
javascriptregexnegative-lookbehind

Javascript regexp that matches '|' not preceded by '\' (lookbehind alternative)


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 .


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 \\|.