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?
You can use optional matches in your regex to cover all 3 cases:
(\d+(?:,\d+)?) x (\d+(?:,\d+)?)(?: x (\d+(?:,\d+)?))?
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.