ErniBrown
ErniBrown

Reputation: 1372

Regex with multiple character separator

I have this string

options{Red | Blue | Green}

And I want to capture the options inside the curly braces one by one. So far I was able to capture the inner part, but I don't understand how to set the pattern SPACELINESPACE | as a separator and capture Red Blue and Green.

For capturing the string inside the curly braces I used this options{(.)*}

I had some results in capturing the values serapately with this:

(.+?)(?: \| |$)

But when I compose everything like this options={(.+?)(?: \| |$)} I do not capture anything

Upvotes: 2

Views: 84

Answers (2)

JvdV
JvdV

Reputation: 75840

Could you use something like:

\w+(?=[^{]*?})

EDIT 1: OP mentioned in the comment below:

"what if I have something like this, options{Red | Blue | green },users={ Paul | Ringo | John | George}? I want to capture just the options."

I'm unsure what flavor is used, but the below pattern will negate the substrings that are found in 'users'.

\busers={.*?}(*SKIP)(*F)|\w+(?=[^{]*?})

See the online demo


EDIT 2:

Without knowing if there are more categories other than 'users' that need to be negated, we could extend the pattern above:

(?<!\boptions){.*?}(*SKIP)(*F)|\w+(?=[^{]*?})

See the online demo

Another way would be to use boost and match substrings using:

(?:\boptions{|\G(?!^))(?:[ |]+)?\K\w+

See the online demo

Upvotes: 2

LogicalKip
LogicalKip

Reputation: 522

You could do the rest in several (non regex) steps : Use your first regex, split on |, and trim.

If you want to do all of it in regex and end up with each color in a different group, it might be more complicated but doable, I'll try for the challenge. Are there always 3 colors ? If so, it's much easier.

EDIT : With only regex, this will do the trick (?!.*\{)([^ |}]+), with the options in group 1

https://regex101.com/r/0Zjzz8/1

Upvotes: 0

Related Questions