regex - Using positive lookahead in Ruby -
i'm writing regular expression following phrase variations:
- "cart total greater $5.00"
- "cart total less $5.00"
- "cart total greater 5.00" (notice no $ in number... what's failing)
i'm capturing 2 things: word "greater" or "less" , amount. want capture amount whether there's dollar sign in or not, what's tripping me up.
here's regexp:
/^.*(?=cart total).*(?=(greater|less)).*(?=\$([0-9.]+))/
this:
"cart total greater $5.00".match(/^.*(?=cart total).*(?=(greater|less)).*(?=\$([0-9.]+))/)
gets me "greater" , 5.00 this:
"cart total greater 5.00".match(/^.*(?=cart total).*(?=(greater|less)).*(?=\$([0-9.]+))/)
get me "greater" , ""
i realize lookahead searching specifcally "$" in group taking out causes not find amount, i'd love see how modify find amount regardless of presence of "$" or not.
thanks!
the lookahead not necessary in case. improved dollar matching match commas in number, e.g., $1,000.00
, , without commas / decimal points, e.g., $10
.
regex = /cart total (greater|less) \$?((?:\d+,?)+(?:.\d+)?)/ strings = [ "cart total greater 5.00", "cart total less $1,500,000.00", "cart total greater $5" ] strings.each |string| p string.match(regex) end #<matchdata "cart total greater 5.00" 1:"greater" 2:"5.00"> #<matchdata "cart total less $1,500,000.00" 1:"less" 2:"1,500,000.00"> #<matchdata "cart total greater $5" 1:"greater" 2:"5">
Comments
Post a Comment