0

I want a regular expression that finds the last match.

the result that I want is "103-220898-44"

The expression that I'm using is ([^\d]|^)\d{3}-\d{6}-\d{2}([^\d]|$). This doesn't work because it matches the first result "100-520006-90" and I want the last "103-220898-44"

Example A
Transferencia exitosa
Comprobante No. 0000065600
26 May 2022 - 03:32 p.m.
Producto origen
Cuenta de Ahorro
Ahorros
100-520006-90
Producto destino
nameeee nene
Ahorros / ala
103-220898-44
Valor enviado
$ 1.000.00

patas1818
  • 93
  • 1
  • 8
  • What do you mean with *"it works in the example B but not in example A"*? The only difference I see is that in A there are two matches, and in B there is just one... – trincot Oct 19 '22 at 20:13
  • I don't know if is possible but in example A I want the second match, can this be achieve by specifying the line breaks ? – patas1818 Oct 19 '22 at 20:17
  • 2
    What is the logic by which you want the **second** match? What is special about it? Or what is wrong with the first one? – trincot Oct 19 '22 at 20:20
  • the second number(second match) is the account I always want to make the transaction not the first number(first match), this is always an account I know. that's why I always want the second match – patas1818 Oct 19 '22 at 20:32
  • 1
    *"I always want the second match"*: So since there is no second match in B, that means you *don't* want to match anything in B, right? – trincot Oct 19 '22 at 20:34
  • 1
    Guess the last match in each block? Try e.g. [`^\d{3}-\d{6}-\d{2}$(?!\n(?:.+\n)*\d+-)`](https://regex101.com/r/zLuWWS/1) – bobble bubble Oct 19 '22 at 20:35
  • To be more clear in example B I want the first math since if you see the possible first match is hidden and the add 100-5* "*" but in example A the fist match I don't need it, I need the second match – patas1818 Oct 19 '22 at 20:39
  • 1
    Do you want the second match, or the last match before an empty line? – The fourth bird Oct 19 '22 at 21:41
  • You are right I want the last match – patas1818 Oct 20 '22 at 12:46

1 Answers1

0
/.*(\d{3}-\d{6}-\d{2})(?:[^\d]|$)/gs

If you add .* to the beginning of your regex, it only captures the last one since it's greedy. Also, you need to use the single-line regex flag (s) to capture new lines by using .*.

Note: I replaced some (...) strings with (?:...) since their aim is grouping, not capturing.

Demo: https://regex101.com/r/fygL1X/2

const regex = new RegExp('.*(\\d{3}-\\d{6}-\\d{2})(?:[^\\d]|$)', 'gs')

const str = `ransferencia exitosa
Comprobante No. 0000065600
26 May 2022 - 03:32 p.m.
Producto origen
Cuenta de Ahorro
Ahorros
100-520006-90
Producto destino
nameeee nene
Ahorros / ala
103-220898-44
Valor enviado
\$ 1.000.00`;
let m;

m = regex.exec(str)

console.log(m[1])
Onur Uslu
  • 1,044
  • 1
  • 7
  • 11