Use of capturing group in .split() function

I have a string and i want to split it into array using the '|' character but not '\|':

var a = 'abc\&|\|cba';
var b = a.split(/([^\\])\|/);

result :

b = ["abc", "&", "|cba"]

expected output :

b = ["abc\&", "\|cba"]

Basically I cannot use capturing groups in .split() function properly.

Answers:

Answer

You could use a positive lookahead for splitting.

With escaped backslash

var a = 'abc\\&|\\|cba';
var b = a.split(/\|(?=\\)/);
console.log(b);

Without escaped backslash

/\|(?=\|)/

  • \| matches the character | literally

  • (?=\|) Positive Lookahead - Assert that the regex below can be matched

    • \| matches the character | literally

Basically it looks for a pipe, and splits if another pipe is following.

var a = 'abc\&|\|cba';
var b = a.split(/\|(?=\|)/);
console.log(b);

Answer

You can do it as follows using regex expressions, storing each identified word( in this case the price) in an array and then grabbing it when needed

var re = /(?:^|[ ])|([a-zA-Z]+)/gm;
var str = 'abc\&|\|cba';
var identifiedWords;

while ((identifiedWords = re.exec(str)) != null) 
{
    if (identifiedWords.index === re.lastIndex) 
    {
        re.lastIndex++;
    }
// View your result using the "identifiedWords" variable.
// eg identifiedWords[0] = abc\&
// identifiedWords[1] = cba

}

Answer

I assume you have a literal \ in your strings, and that your question contains a typo in the input string literal. In JS C strings, you need to use a double \ to define a literal backslash (since in regular string literals, you can define escape sequences like \r, \n, etc).

Your regex needs to match all characters other than \ and | or any literal \ followed with any letter. If your string can equal a literal \, you need

var a = 'abc\\&|\\|cba';
b = a.match(/(?:[^\\|]|\\.?)+/g);
console.log(b);

The pattern matches:

  • (?: - (start of a non-capturing alternation group)
    • [^\\|] - any char other than \ and |
    • | - or
    • \\.? - a \ followed with any 1 or 0 chars but a newline
  • )+ - 1 or more times

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.