unwise guy
unwise guy

Reputation: 1128

Regular expression with a small bug

I have this string

hey {Bobby|Apple|Peter}, nice to meet you {David}

and this regex:

(\{(\w+)(\|(\w+))*)\}

the answer:

Bobby
Peter
David

However, it's not getting "Apple", how can I fix this to get it as well?

Thanks!

Upvotes: 1

Views: 85

Answers (2)

Maarten Bodewes
Maarten Bodewes

Reputation: 94118

Repetition does not work for groups. Instead, try to iteratively use find on the string. Probably best to first filter out {Bobby|Apple|Peter}, get the names from that, then find {David} and get the names from that. So that would be two finds, if you keep using regular expressions. Or one find, then a split on | from the result.

Regexp for the find: \{(\w+(?:\|\w+)*)\}, then use group 1 (everything within the braces) and split the result.

Upvotes: 1

hcarver
hcarver

Reputation: 7234

Can you show the entire, minimal code that reproduces this problem? It's possible the problem is with how you're iterating through the captured groups.

Upvotes: 0

Related Questions