Do not accept duplicate values in a Regular Expression (Regex)

1

I have the following code:

var str = "141271999 243306211 172266710 172266710 172266710";
var regex =  /[0-9]{9}/g; //Encontrar 9 números entre 0-9 e retornar todos valores (g).
var idsEncontrados = str.match(regex);

How can I configure my regex to disregard the duplicate values found by having my idsEncontrados receive only the 141271999, 243306211, 172266710 values?

    
asked by anonymous 22.05.2018 / 14:51

1 answer

3

You can use the following regex:

([0-9]{9})(?!.*)

See it working on regex101

Explanation:

(        - primeiro grupo de captura
[0-9]{9} - 9 digitos de 0 a 9
)        - fecha o grupo de captura
(?!      - Negative lookahead, que não tenha à frente
.*       - qualquer coisa
)      - seguida do que foi capturado no grupo 1

Example in code:

var str = "141271999 243306211 172266710 172266710 172266710";
var regex =  /([0-9]{9})(?!.*)/g;
var idsEncontrados = str.match(regex);

console.log(idsEncontrados);

However, as @AndersonCarlosWoss mentioned, it's an easy logic to implement directly in Javascript, using the filter function.

See the related question: Remove repeated elements within of a vector in javascript

    
22.05.2018 / 15:05