Match product dimensions with regular expression

Deadly 提交于 2020-01-23 02:12:26

问题


I am trying to match length width and height with a regular expression.

I have the following cases

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

The second case can be matched with (\d+) x (\d+) x (\d+), which works fine.

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?


回答1:


You can use optional matches in your regex to cover all 3 cases:

(\d+(?:,\d+)?) x (\d+(?:,\d+)?)(?: x (\d+(?:,\d+)?))?

RegEx Demo

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+)?)

Which is 1 or more digits optionally followed by a comma and 1+ digits for decimal part.

Also, note that height part is an optional match as we're using (?: x (\d+(?:,\d+)?))? to make that part optional.




回答2:


As simple as:

^Produktabmessungen\K(.+)

See a demo on regex101.com (and mind the different modifiers!).
You do not really need the \K in this situation but will need the multiline flag. What language are you using?



来源:https://stackoverflow.com/questions/39452200/match-product-dimensions-with-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!