Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression: capture group might not exist. How do I write it?

Tags:

regex

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.

like image 636
Octopus Avatar asked Sep 05 '25 02:09

Octopus


1 Answers

You can make 2nd group lazy and use line end as alternate match in 3rd group:

(\d+)\s+-\s*(.+?)\s*(\(.*\)|$)

RegEx Demo

like image 52
anubhava Avatar answered Sep 07 '25 22:09

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!