Search code examples
regexregex-group

Regex repeating a capturing group not returning the last one


I've read this and that but my regex still doesn't work - it returns the first match where I expect it to return the last one.

The goal is to extract the last number before x char and the first number after it.

My regex so far is ((\d+)+).*x(\d)

Test input: 1x2x3x4

Expected result: 2 groups? (with 3 and 4)

Actual result: 3 groups?! (1, 1, 4)


Solution

  • You can capture the digits in 2 groups with an x char in between at the end of the string

    (\d+)x(\d+)$
    

    See a regex demo

    Or without the anchor, if a lookbehind is supported:

    .*(?<!\d)(\d+)x(\d+)
    

    Regex demo