Avatar of MJ
MJFlag for United States of America asked on

Need regex for separator

what regex would I use to get separate values on a pipe ("|") separator? It has to be a regex, not a split etc.

Example:

abc|def|ghi
abc|def|ghi|jkl
123|456|789
123|456|789|101112
one1|two2|3three|4four|five5
JavaScript

Avatar of undefined
Last Comment
Rob

8/22/2022 - Mon
Terry Woods

You could do it with a single regex if you had a fixed limit of the number of values.
eg something like this:
/^([^|]*)\|?([^|]*)\|?([^|]*)\|?([^|]*)\|?/

If you had essentially a while loop or recursive function, you could keep matching with the pattern:
/^([^|]*)\|(.*)/

Open in new window

and add the first match to an array then repeat the above on the 2nd match.
Terry Woods

Anyway, what's wrong with a split? Do you need to handle escaped | characters or something like that?
Rob

Whether you do a reflex or split you'll end up with an array of your values. Please explain the reason behind not so putting the array. You can always join it back together later if you need to
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
ASKER
MJ

i'm using a tool which requires a regex. What about this:

^.+\|(.+)\|(.+)|(.+) and I take $2? I'm just looking to identify the third segment of a pipe delimited string.
Rob

That makes sense. Ignore my last comment
ASKER
MJ

how do I account for situations where there may at times be additional pipes after 2nd one? I only want the third segment

^.+\|(.+)\|(.+)\|(.+)

abc|def|ghi
abc|def|ghi|jkl
123|456|789
123|456|789|101112
one1|two2|3three|4four|five5
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
SOLUTION
Rob

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
MJ

Hi Tagit,
How do I get it to run here http://regexpal.com/
ASKER CERTIFIED SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Rob

Thanks Terry