I’ve been banging my head against the wall for hours trying to figure this out. I’m trying to capture three groups if they’re there and if not, capture everything in the first group. I can break this out into separate regex statements but keeping one would be awesome.
The 4 different strings would be like the following:
Be somewhere now & be there later (Store) @1300
Be at work! @1430
Go home whenever (Home)
Don't ever go to the donut shop.
The end result I’m looking for is like the following:
(Group 1) Be somewhere now & be there later (Group 2) Store (Group 3) @1300
(Group 1) Be at work! (Group 2) (Group 3) @1430
(Group 1) Go home whenever (Group 2) Home (Group 3)
(Group 1) Don't ever go to the donut shop. (Group 2) (Group 3)
The best I can do so far is handle the 1st and 2nd option and only grabbing Group 3. I’ve done this with this:
.*(?:\(.*\))?\s(\@\d+)$
I’m pretty sure the .* is going to have to be removed because if I turn it into (.*) it always matches everything.
I’ve tried every which way I know but can’t get it to work so now I reach out to you. 🙂
Try this:
The key is that
.*?is a non-greedy match. It will match as little as possible, so it won’t match the entire string unless the other groups fail to match.See it working online: rubular