Regex match everything after conditional match

Viewed 115

am looking to match everything before (and after) zero or more from a list of items. Here is what I am currently using: (?<=\))(.*)(?=(or|,|\())

In this case, I want to match everything after a closing parenthesis ) and everything before or , or ). This works ok (probably not optimally), however, if there are none of the 3 items match, there are no matches.

For example, the sentence 2 cups (500 ml) mushroom, or vegetable broth matches for mushroom, however, 2 cups (500 ml) mushroom doesn't match anything.

Basically, my goal is to find the ingredient from the ingredient + qty string, with the above sentence matching mushroom and the sentence salt matching the whole string salt

Here are more examples:
1 thyme sprig should match thyme sprig
1 garlic clove, chopped should match garlic clove
1 cup (180 g) quinoa, rinsed and drained should match quinoa
2 tbsp (30 ml) olive oil, plus more for serving should match olive oil
Vegan Parmesan, to taste returns Vegan Parmesan

The difference between the first 2 and last 2 is tricky, as if there is a closing parenthesis (as in the last 2 examples), the ingredient should be after the closing parenthesis. If there are no closing parenthesis (as in the first 2 examples, everything after the number should be taken.

2 Answers

You can use

(?:^[^)\n]*\)|\d)\s*\K.*?(?=or|[,(]|$)

If your regex flavor does not support \K, use a capturing group:

(?:^[^)\n]*\)|\d)\s*(.*?)(?=or|[,(]|$)

See the regex demo. Get Group 1 value.

Details:

  • (?:^[^)\n]*\)|\d) - either start of string and then zero or more chars other than a newline or ) char and then a ) char, or a digit (if there is no ) on the line)
  • \s* - zero or more whitespaces
  • (.*?) - Group 1: any 0+ chars other than line break chars, as few as possible
  • (?=or|[,(]|$) - up to the first occurrence of or, ,, (, or end of string.

Add |$ (end of string) to the ending group: (?<=\))(.*?)(?=(or|,|\(|$))

Edit: After testing here, I found you also need to make the main group non-greedy.

Related