Link to home
Start Free TrialLog in
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
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

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.
Anyway, what's wrong with a split? Do you need to handle escaped | characters or something like that?
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
Avatar of MJ

ASKER

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.
That makes sense. Ignore my last comment
Avatar of MJ

ASKER

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
SOLUTION
Avatar of Rob
Rob
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MJ

ASKER

Hi Tagit,
How do I get it to run here http://regexpal.com/
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks Terry