-2

I'm trying to use regex to match numbers with thousand separators, but only if they are preceded with a -$

For example, I would like to match

-$1,200
-$750

But not

$1200
$750

From other answers, I'm able to use [0-9]{1,3} to match numbers with thousand separators, but I can't figure out how to limit to only cases that are preceded with -$. -\$[0-9]{1,3} doesn't work.

Example on regex101

The particular string that I'm trying to get it to work on:
{"amount":1242,"amountFormatted":"-$1,242","currency":"USD","type":"PRICING","__typename":"PriceItem"},{"localizedTitle":"Fees","localizedExplanation":"This fee covers: "} 
Harry M
  • 1,848
  • 3
  • 21
  • 37
  • What language or Regex flavor are you using? – esqew Sep 11 '19 at 00:16
  • would like to make it work on regex101. example https://regex101.com/r/9HM1qw/1 – Harry M Sep 11 '19 at 00:16
  • Possible duplicate of [Regex for number with decimals and thousand separator](https://stackoverflow.com/questions/16148034/regex-for-number-with-decimals-and-thousand-separator) – esqew Sep 11 '19 at 00:19
  • It's a different question because it asks about matching a pattern before the number – Harry M Sep 11 '19 at 00:23
  • By SO standards, I think it'd still be considered a duplicate, as the underlying premise is still the same. The changes required to get the solutions listed on that question working in this context are minimal. – esqew Sep 11 '19 at 00:27
  • I showed an example of the minimal changes I believed are necessary and how it doesn't provide a solution – Harry M Sep 11 '19 at 00:31

1 Answers1

1

This regex should do the trick: ^-\$\d{1,3}(?:,\d{3})*$ Between the start and end of the line, it first looks for -$ literally, then 1-3 digits, and then groups a comma and 3 digits, capturing this group as many times as needed.

Try it here!

EDIT: If you want to match between quote marks, as suggested by Bohemian, this regex is likely what you want: "-\$\d{1,3}(?:,\d{3})*" - it behaves just as the other, but searches between quote marks, instead of between the start and end of the string.

Try it here!

Nick Reed
  • 4,989
  • 4
  • 17
  • 37
  • This works! Do you know why it does not work on this particular string? `{"amount":1242,"amountFormatted":"-$1,242","currency":"USD","type":"PRICING","__typename":"PriceItem"},{"localizedTitle":"Fees","localizedExplanation":"This fee covers: "} ` – Harry M Sep 11 '19 at 00:24
  • 1
    @Harry It doesn't match because you didn't ask it to match *within a string*, you asked for the *whole* string to match - there are start and end anchors in this answer. You could possibly replace `^` and `$` with `"` and see if it works for you. – Bohemian Sep 11 '19 at 00:25
  • 1
    @HarryM see updated answer - looks like it should match your requirements. – Nick Reed Sep 11 '19 at 00:43