-1

The regex is matching the currency properly, for instance $42,000,000 . However, if I write aaaa$42,000,000 or $42,000,000aaa or aaa$42,000,000aaaa it's also matching it which shouldn't be the case, it should match only when there are spaces around.

The regex I have is /\$(([1-9]\d{0,2}(,\d{3})*)|0)?(\,\d{1,2})?/g

I also tried with /\b\$(([1-9]\d{0,2}(,\d{3})*)|0)?(\,\d{1,2})?\b/g but it's not working. Any suggestions?

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • 1
    If you tag your question with the language of your source code, then you might get a better answer. This is especially true if you haven't yet considered solution A of zx81's [answer](https://stackoverflow.com/a/24378033/1707353). – Jeff Holt Sep 08 '20 at 16:24
  • 1
    Alternative regex: "(?:^|\\s)(\\$\\d+[,\\d]+\\d)(?:$|\\s)". Use matcher.group(1). – DigitShifter Sep 08 '20 at 16:57
  • I don't think this kind of question is a good fit for stackoverflow. Try to break it into pieces and make each piece as generic as possible. So that other users can benefit of the answer if we arrive at one. – Tomas Zubiri Sep 09 '20 at 01:33

2 Answers2

0

You may use the following pattern:

(?<!\S)\$\d{1,3}(?:,\d{3})*(?:\.\d+)?(?!\S)

Demo

Explanation:

(?<!\S)      assert that what precedes is either whitespace or the start of the input
\$           match $
\d{1,3}      match 1-3 digits
(?:,\d{3})*  match zero or more thousands terms
(?:\.\d+)?   optional decimal component
(?!\S)       assert that what follows is either whitespace or the end of the input
Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263
0

I'd suggest this regex:

^\$\d{1,3}(?:(?:\.|\,)\d{3})*$
  • ^\$\d{1,3}: line must start with a dollar sign followed by 1 up to 3 digits
  • (?:(?:\.|\,)\d{3})*$: line can end with an unlimited (or zero) repetition of 3 digits preceded by a comma or a dot

Demo: https://regex101.com/r/BBWlIF/2

Sumak
  • 394
  • 1
  • 14