Carol.Kar
Carol.Kar

Reputation: 5355

Match product dimensions with regular expression

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?

Upvotes: 4

Views: 3820

Answers (2)

anubhava
anubhava

Reputation: 785721

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.

Upvotes: 5

Jan
Jan

Reputation: 43169

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?

Upvotes: 1

Related Questions