圆环黑石效果陶瓷地砖,9 件装,(长)333 毫米(宽)333 毫米
我创建了一个 block ,它循环访问一组结果,我需要匹配长度 (L)333mm 和宽度 (W)333mm,以便我可以将它们添加到数据库中。
我已经尝试了一些正则表达式,但现在没有一个有效,感觉就像我只是在猜测。
product_description = product.at_css('h3 a').text[/\L[0-9\.]+mm/]
给出nil
,你能给我指出正确的方向吗
最佳答案
这是一个无序的 len/width 正则表达式,一次通过即可获得两者。
取决于条件,所以这取决于 Ruby 是否支持它们。
这些值位于各自的命名组中。
编辑
对于Ruby,乱序可以这样搞。
请注意,大多数引擎都允许您在解析之前引用一个组。
使用 Ruby,您至少必须在组的开头处在里面
能够引用它的(当前)内容。
(?:\s*(?:\(W\)(?<width>(?(<width>)(?!))[\d.]+)(?<width_unit>[cm]?m|in|ft)|\(L\)(?<len>(?(<len>)(?!))[\d.]+)(?<len_unit>[cm]?m|in|ft))){1,2}
http://rubular.com/r/SMw5bxHVYv
格式化
(?:
\s*
(?:
\(W\)
(?<width> # (1 start), Width
(?(<width>) # Conditional, cannot match width again
(?!)
)
[\d.]+
) # (1 end)
(?<width_unit> [cm]? m | in | ft ) # (2)
| \(L\)
(?<len> # (3 start), Len
(?(<len>) # Conditional, cannot match length again
(?!)
)
[\d.]+
) # (3 end)
(?<len_unit> [cm]? m | in | ft ) # (4)
)
){1,2} # Must match one or two
对于其他引擎,您可以将条件放在组定义之前。
(或在组的开头,如上所述)
(?:\s*(?:(?(<width>)(?!))\(W\)(?<width>[\d.]+)(?<width_unit>[cm]?m|in|ft)|(?(<len>)(?!))\(L\)(?<len>[\d.]+)(?<len_unit>[cm]?m|in|ft))){1,2}
https://regex101.com/r/VyCqjt/2
格式化
(?:
\s*
(?:
(?(<width>) (?!) ) # Conditional, cannot match width again
\(W\)
(?<width> [\d.]+ ) # (1)
(?<width_unit> [cm]? m | in | ft ) # (2)
|
(?(<len>) (?!) ) # Conditional, cannot match length again
\(L\)
(?<len> [\d.]+ ) # (3)
(?<len_unit> [cm]? m | in | ft ) # (4)
)
){1,2} # Must match one or two
关于Ruby 正则表达式匹配维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48547538/