How might I efficiently use regex to match input that could be a positive or negative dollar amount or percentage.
- Input could start with optional + or -
- Followed by optional $
- Then digits with optional comma as a digit group separator following a digit in the thousands/hundred thousands/millions...
- Followed by an optional decimal point and one or two digits
- And finally a possible %, but only if the input doesn't contain a $, and the number is from -100.00 to +100.00
So it would match input like: 12, -60, $25.50, -$1.5, +$25,000, 5.5%, -100%, +100%, 0.01%
And return false with input like: Text, +$10%, -5.001
I've been evaluating them separately with:
function percentValue(input) {
regex = /^[+-]?\$?(?=.)(\d*|\d{1,3}(,\d{3})*)?(\.\d{1,2})?$/;
return regex.test(input);
}
function dollarValue(input) {
regex = /^[+-]? *100(\.0{0,2})? *%?$|^[+-]? *\d{1,2}(\.\d{1,2})? *%?$/;
return regex.test(input);
}
Results
percentValue('5.5%'); // True
percentValue('-100%'); // True
percentValue('+.01%'); // True
percentValue('0.001'); // False
percentValue('101%'); // False
percentValue('$100%'); // False
dollarValue('+$12'); // True
dollarValue('-$60.5'); // True
dollarValue('$25,000'); // True
dollarValue('-$5.001'); // False
dollarValue('1,00.25'); // False
dollarValue('$text'); // False
I've been unsuccessful trying to combine them into one. Should I be using another lookahead for the percentage?