Regex for item dimensions

Viewed 34

I have this regex:

(\d+\.?\d*)(?=.*)(\d+\.?\d*)|(\d+\.?\d*).+diam

However, it's not working fully. It's picking up '24K Gold' It should only pick up 2 valid numbers with an x in the middle somewhere.

Current regex output

EDIT:

Examples:

Input:

40cm x 100cm

2.3 x 8.6

height: 100cm x width: 200.2cm

25K Gold

60 diam

50 diam

Output:

40, 100

2.3,8.6

100,200.2

60

50
2 Answers

For this single numbered text like:

25K Gold

60 diam

50 diam

/(\d+(\.\d+)?)/

And for two numbered text like:

40cm x 100cm

2.3 x 8.6

height: 100cm x width: 200.2cm

/(\d+(\.\d+)?).*?x.*?(\d+(\.\d+)?)/

your first and second number will be in the first and second capturing group consequently.

To get the value with an x in between, and not match 25K Gold, 60 diam and 50 diam you could use

\b(\d+(?:\.\d+)?)[^\dxX\n]*[xX][^\dxX\n]*(\d+(?:\.\d+)?)

The pattern matches:

  • \b A word boundary to prevent a partial match
  • (\d+(?:\.\d+)?) Capture group 1, match 1+ digits with an optional decimal part
  • [^\dxX\n]*[xX][^\dxX\n]* Optionally match any char except x or X and then match x
  • (\d+(?:\.\d+)?) Capture group 2, match 1+ digits with an optional decimal part

Regex demo

Related