Albeis
Albeis

Reputation: 1580

Capturing optional groups regex expressions Php

I almost have the full regex expression, but, there is a case that i'm not able to match.

I need to capture: The xxxx word if exist, the decimals (30), and the 'cm'.

I have expressions like:

30x30cm

30 x 30 cm

30x30 cm

xxxx 30x30cm

xxxx (30x30cm) -> That case does not match the word xxxx (if exist I need to capture)

xxxx (30 x 30 cm)->That case does not match the word xxxx (If exist I need to capture)

Thats my regex nowadays:

(?:(\w+))?\s?\b(\d+)\s?x\s?(\d+)\s?(cm)\b

How I can match with the word xxxx if exist? Any help would be appreciated

[https://regex101.com/r/morihH/1][1]

Upvotes: 1

Views: 69

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627469

You may add optional whitespaces and a ( to the first optional non-capturing group:

(?:(\w+)\s*\(?)?\b(\d+)\s?x\s?(\d+)\s?(cm)\b
        ^^^^^^

See the regex demo (\s replaced with a space since the input string is a multiline one).

The \s*\(? match 0+ whitespaces followed with an optional (.

Upvotes: 1

Related Questions