4

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?

Carol.Kar
  • 4,581
  • 36
  • 131
  • 264
  • `\\ ` escapes the backslash and matches the character `\ ` literally. Also your third case has only 2 dimensions while your expression expects 3. – Phu Ngo Sep 12 '16 at 14:08

2 Answers2

5

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

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?

Jan
  • 42,290
  • 8
  • 54
  • 79