用正则表达式匹配产品尺寸 [英] Match product dimensions with regular expression
问题描述
我正在尝试使用正则表达式匹配长度宽度和高度.
I am trying to match length width and height with a regular expression.
我有以下情况
Artikelgewicht3,7 Kg
Produktabmessungen60,4 x 46,5 x 42 cm
or
Artikelgewicht3,7 Kg
Produktabmessungen60 x 46 x 42
or
Artikelgewicht3,7 Kg
Produktabmessungen60 x 46
第二种情况可以搭配(\d+) x (\d+) x (\d+)
,效果很好.
The second case can be matched with (\d+) x (\d+) x (\d+)
, which works fine.
我进一步尝试将第一种和第三种情况与 (\d+)(\\,\d+)?x (\d+)(\\,\d+)?x (\d+)(\\,\d+)?
.
I further tried to match the first and the third case with (\d+)(\\,\d+)? x (\d+)(\\,\d+)? x (\d+)(\\,\d+)?
.
任何建议我做错了什么?
Any suggestions what I am doing wrong?
推荐答案
您可以在正则表达式中使用可选匹配来涵盖所有 3 种情况:
You can use optional matches in your regex to cover all 3 cases:
(\d+(?:,\d+)?) x (\d+(?:,\d+)?)(?: x (\d+(?:,\d+)?))?
这将在第一个捕获组中给出length
,在第二个捕获组中给出width
,在第三个捕获组中给出height
.
This will give length
in 1st capturing group, width
in 2nd capturing group and height
in 3rd.
每个组都使用这个子表达式:
Each group is using this sub-expression:
(\d+(?:,\d+)?)
1 个或多个数字可选后跟一个逗号和 1 个以上的小数部分.
Which is 1 or more digits optionally followed by a comma and 1+ digits for decimal part.
另外,请注意高度部分是可选匹配,因为我们使用 (?: x (\d+(?:,\d+)?))?
使该部分成为可选.
Also, note that height part is an optional match as we're using (?: x (\d+(?:,\d+)?))?
to make that part optional.
这篇关于用正则表达式匹配产品尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!