Reputation: 189
I'm making a Chrome extension that searches a page for a dollar amount (a number with no more then two decimal places immediately preceded by a "$") then tacks on a bit with how much that value would be in another currency. I found a commonly used regex that matches exactly those parameters.
/^\$?\-?([1-9]{1}[0-9]{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\-?\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\(\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))\)$/g
so I'm thinking I have a nice headstart. I've only been coding a couple of months and of all the concepts I've encountered, regex's give me the most headache. I test out my shiny new expression with:
var regex = /^\$?\-?([1-9]{1}[0-9]{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\-?\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\(\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))\)$/g;
var str = "The total it $2.25 Would you like paper or plastic?";
r = regex.test(str);
console.log(r);
and of course that sucker returns false! I tried a few more strings with "2.25" or "$2" or "$2.256" just to be sure and they all returned false.
I am thoroughly stumped. The expression came recommended, I'm using .test() correctly. All I can think of is it's probably some small newbish detail that has nothing to do with regex's.
Thanks for your time.
Upvotes: 1
Views: 493
Reputation: 42717
Your overly complex regular expression is checking the entire string. Remove the ^
and $
which denote the beginning and end of the string, respectively. Then remove the /g
flag, which is used to search for multiple matches.
What's wrong with checking for /\$\d+\.\d\d/
?
I find http://regex101.com/ to be a helpful resource.
Upvotes: 1