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.

5
  • 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. Commented Oct 25, 2018 at 14:36
  • @gbeaven I tried the split method with string.split([',','|']) and got nowhere. Can you give an example? Commented Oct 25, 2018 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. Commented Oct 25, 2018 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. Commented Oct 25, 2018 at 14:42
  • I see. It would be appropriate to use regex in the case where you are searching for more than 1 delimiter. Commented Oct 25, 2018 at 14:47

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

2 Comments

btw, split is always global.
@NinaScholz, thanks for the very important point.....
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!

3 Comments

Thanks for the links. Having a look now.
As stated, no need for the +, the split() takes all it finds
in case if we have two | like: b = 'A,B||C,D', then it will produce additional one empty string

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.