Here are some examples of the strings I need to parse:
1 - Cream Soda (0.99)
5 - Potato Chips (2.50)
12 - Atlantic Salmon
I want to capture the first numeral, the product name and the price including parentheses. Sometimes the price and associated parentheses don't exist.
I came up with this regex:
/(\d+)\s+-\s*(.+)\s+(\(.*\))/
which works only when all three groups exist. I also tried this:
/(\d+)\s+-\s*(.+)\s+(\(.*\))?/
but its not any better.
How do I make the third capture group optional?
This is in javascript if it makes any difference.
You can make 2nd group lazy and use line end as alternate match in 3rd group:
(\d+)\s+-\s*(.+?)\s*(\(.*\)|$)
RegEx Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With