3

I am not good at regex, thats why I ask here.

Suppose I have the following strings:

let a = 'A,B,C,D', 
    b = 'A,B|C,D',
    c = 'A|B|C|D'

I'd like to split them using a comma ,, and a pipe |. Something like:

// a.split(regex)

Or similar while considering the performance.

All the above strings should result in // [A, B, C, D]

How would I write a regex for that. Also, a reference to teach myself regex would be welcome.

Nelson Owalo
  • 2,324
  • 18
  • 37
  • I know you asked for a regex solution, but wanted to give you an alternate just in case you think that's the ONLY way to achieve this. It's not. You would be able to get the same results by just specifying your delimiter in the split() method: `a.split("|")` and not having to waste resources by spinning up the regex engine for such a simple task. – gbeaven Oct 25 '18 at 14:36
  • @gbeaven I tried the split method with `string.split([',','|'])` and got nowhere. Can you give an example? – Nelson Owalo Oct 25 '18 at 14:38
  • `let a = 'A|B|C|D',result = a.split('|') console.log(result);` Gets you the same results being posted below using regex. – gbeaven Oct 25 '18 at 14:40
  • @gbeaven - I corrected my question. It was a bit confusing. I want to split with both `,` and `|`. `.split()` can take an array but just doesn't seem to work. – Nelson Owalo Oct 25 '18 at 14:42
  • I see. It would be appropriate to use regex in the case where you are searching for more than 1 delimiter. – gbeaven Oct 25 '18 at 14:47

2 Answers2

4

Try RegEx /[,|]/

By placing part of a regular expression inside round brackets, you can group that part of the regular expression together.

Here ,| matches a single character in the list.

let a = 'A,B,C,D', 
    b = 'A,B|C,D',
    c = 'A|B|C|D'

a = a.split(/[,|]/);
b = b.split(/[,|]/);
c = c.split(/[,|]/);

console.log(a);
console.log(b);
console.log(c);
Mamun
  • 66,969
  • 9
  • 47
  • 59
4

You can try this:

str.split(/[|,]+/)

Here, regex specifies that | and , can occur 1 or more times and if found it will split function will do the job.

This is the best tool when it comes to testing regex: https://regex101.com/

I learned my regex here: https://regexr.com/

Hope this helps!

AkshayM
  • 1,421
  • 10
  • 21