how to find the second number in a string with Regex expression

82 Views Asked by At

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

1

There are 1 best solutions below

0
Onur Uslu On
/.*(\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])