我难以将字符串“79¢/ lb”与此正则表达式匹配:(\ $ |¢)\ d +(。\ d {1,2})?
当分符号出现在开头时,它工作正常,但我不知道在字符串末尾附近需要添加什么。
基本上我打算从这个价格标签中提取浮动值,即0.79,提前感谢,我正在使用红宝石。
答案 0 :(得分:1)
那么,正则表达式要求$
或¢
位于字符串的开头。要匹配79¢ /lb
,您需要以下内容:
(\d+)¢
后,¢
来自。
匹配您可能会看到的各种格式的单一正则表达式会更复杂一些。我建议将其作为多个正则表达式(为简单起见),或在此处询问另一个问题,指定要从中捕获价格的全部字符串。
答案 1 :(得分:1)
当您分别考虑每个案例时,最容易找出正确的正则表达式。如果我理解你的问题,有4个案例:
首先,分别为每个案例写一个正则表达式:
¢(\d{1,2})\b
\b(\d{1,2})¢
\$(\d+(?:\.\d{2})?)\b
\b(\d+(?:\.\d{2})?)\$
然后,将它们组合成一个正则表达式:
regex = %r{
¢(\d{1,2})\b | # case 1
\b(\d{1,2})¢ | # case 2
\$(\d+(?:\.\d{2})?)\b | # case 3
\b(\d+(?:\.\d{2})?)\$ # case 4
}x
然后,匹配你心中的内容:
string_with_prices.scan(regex) do |match|
# If there was a match in the first two groups, it's for cents
cents = $1 || $2
# ...and the last two groups are dollars.
dollars = $3 || $4
if cents
puts "found price (cents): #{cents}"
elsif dollars
puts "found price (dollars): #{dollars}"
else
puts 'unknown match!'
end
end
注意:要测试此代码,我必须使用'c'而不是'¢',因为Ruby告诉我invalid multibyte char (US-ASCII)
。要避免此问题,请使用不同的字符编码,或者计算'¢'字符的编码值并将其直接嵌入正则表达式中,例如%r{\x42}
代替%r{¢}
。
答案 2 :(得分:0)
也许你不需要在你的reg exp中做任何事情;
#price is the string that contains the price
if price =~ /\$|¢/
value = string.match(/\d+/)
end
或类似的东西。