Skip to main content

Regexp for prices or how to detect price in a smart way

Ruby • Asked by eelcoj

Any regexp experts here? I have the following situation:

  • get an invoice
  • scan it for prices and save the highest number
  • success 🍾

I do this with a .scan(/…/). Pretty fast in Ruby. ✨

Format of pricing, and thus why the regexp gets tricky, can be really all over the place, some examples:

€ 59,95
$ 100
$ 10.00
29 €
49,95 €
50 $

And any combination of above, including different type of spaces between currency and number :)

Current regexp looks like this, but that doesn't take into account the currency symbol after the price: /([€$]{1}[ \s]?)(\d{1,6}([,.]\d{1,2})?)/.

I am starting to think I need to think outside of using just regexp and need some ruby magic here, but hope any of you smart folks can help with that too.

Edit: just typing this post, I got the idea of separating the two. Scan for currency symbol first and then check for highest price. 💡

Hey Jack,

Did you ever come up with a clean solution for this?

I think your final edit (separating the two first) is probably the way I would have tried to tackled it, although my regex skills are horrid... Do you account for currency conversion rates to determine if a value is really higher than the other, or is it purely based on the face value?

Yes, the edit is the way I went for. Per invoice there's just one currency, so no need for conversion there.
I've been upping my regexp skills since this feature.
Really now just need to whip up something to easily test against various cases, since I do it manually now 😅

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 22,346+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.