1

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)

Nikola
  • 101
  • 7

1 Answers1

1

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

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • 1
    @bobblebubble :-) That `.*` needs a brake somehow or else you capture only the last digit – The fourth bird Nov 08 '22 at 16:37
  • Wow, thank you! The groups could be anywhere and they could be surrounded by other chars (i.e. can't use the anchor). Lookbehind is supported so I'll look into that. Thank you again! – Nikola Nov 08 '22 at 18:19
  • Any idea why the repeating capturing group is returning the first match instead of the last one? (all docs are saying it should return the last iteration) – Nikola Nov 08 '22 at 18:20
  • 1
    @Nikola In this case they are 2 different things. If you look at this example https://regex101.com/r/XwlxZ3/1 you see that you repeat a capture group that by itself matches a single digits. Now repeating the group, you can see that only the last digit is captured in group 1. The first pattern in the answer has an anchor at the end of the string, and there are no repeated groups. The second pattern uses first `.*` to match to the end of the string. Then it will backtrack until it can match the first occurrence of the pattern `(\d+)x(\d+)` and here are also no repeated capture groups. – The fourth bird Nov 08 '22 at 20:13
  • For some reason, despite the +, the first match group match only single digits. Here's an example: https://regex101.com/r/AHwL6v/1 Any idea why? – Nikola Nov 08 '22 at 21:47
  • 1
    @Nikola You are over using `.*` Remember that it will first match until the end of the string and then allows backtracking. In this part `.*(\d+)` the `.*` can backtrack to allow 1 digit (which is allowed by `\d+` as it matches 1 or more digits) and that is why you have a single digit in the capture group. – The fourth bird Nov 08 '22 at 21:51