Search code examples
regexregular-language

Match middle and end of length x width x height


I am trying to match, the following cases:

1. Get either between or if only one x exists the end

Example:

| Matches/Cases     | Result |
|-------------------|--------|
| 200 x 90 x 14     | 90     |
| 90x200            | 200    |
| 200 x 90x20       | 90     |
| 60,4 x46,5 x 42,6 | 46,5   |
| 90x190,9          | 190,9  |

2. Get if two x exist the final one, and if only one exist no result

Examples:

| Matches/Cases     | Result |
|-------------------|--------|
| 200 x 90 x 14     | 14     |
| 90x200            | -      |
| 200 x 90x20       | 20     |
| 60,4 x46,5 x 42,6 | 42,6   |
| 90x190,9          | -      |

I stuck at getting one specific case! I tried to match with the following regex x\s?((\d+(?:,\d+)?))\s?, but I still get only the last part of the cases like for 90x200 I get 200, but for 200 x 90 x 14 I get 90 x 14.

Any suggestions of two regex that works for case 1 or case 2?

I appreciate your replies!


Solution

  • I tried to match with the following regex x\s?((\d+(?:,\d+)?))\s?, but I still get only the last part of the cases.

    Actually by your own RegEx you are going to capture all digits or floats followed by a x. So it's not only last part but all similar occurrences.

    Solution (main regex):

    (?: *(\d+(?:,\d+)?) *(?:x|$))
    

    If you want it for case #1 then append quantifier {2}

    (?: *(\d+(?:,\d+)?) *(?:x|$)){2}
    

    Live demo

    If you want it for case #2 append quantifier {3}

    (?: *(\d+(?:,\d+)?) *(?:x|$)){3}
    

    Live demo

    m modifier should be set in both cases