3zzy 3zzy - 1 month ago 6
PHP Question

Regex for object dimensions

http://regexr.com/3eg8c

Text:

(18.8 x 25.7 x 1.8 cm)
10.787 x 8.031 x 1.339"
2.75 x 6.5 x 6.5 in
31 x 21.89 x 1.89 cm
(18.8 x 25.7 x 1.8 cm)
10.787 x 8.031 x 1.339"
2.75 x 6.5 x 6.5 in
31x21.89x1.89 mm


Expression:

/(\d*\.?\d+) x (\d*\.?\d+)(?: x (\d*\.?\d+))\s*(cms?|in|inch|inches|mms?)\b/ig


Currently matches some of the values from my test case, but i'd like it to:


  • Make sure exactly 3 values are found (1x2x3) no more, no less.

  • Ignore spaces between the numbers as well as the number and unit.

  • Include unit in the capture group.


Answer

This change will give you what you are looking for:

/^(?:[\(])?(\d*\.?\d+)\s*x\s*(\d*\.?\d+)\s*x\s*(\d*\.?\d+)\s*((?:cms?|in|inch|inches|mms?)\b|(?:[\"]))/igm

You can check here:
http://regexr.com/3eg8i

This is the breakdown:

  1. start at the beginning of the string ^ (or beginning of line, using the /m modifier at the end)
  2. allow ( but don't catch it (?:[\(])
  3. find a number (\d*\.?\d+) (int or float [with the dot])
  4. have the x char, with (or without) space before and after `\sx\s - support multiple spaces here
  5. have any of the supported units:
    5.1 cm, cms, in, inch, inches, mm, mms - followed by word boundry
    (?:cms?|in|inch|inches|mms?)\b
    OR
    5.2 Have the " char |(?:[\"])
Comments