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

Asked

Viewed 319 times

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 set my regex to disregard duplicate values found by making my variable idsEncontrados receive only the values 141271999, 243306211, 172266710?

  • It’s not easier implement this logic filtering the repeated in idsEncontrados?

  • is a possibility...but I imagine there might be some flag or something like that to set up the regex this way.

1 answer

3


You can use the following regex:

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

See 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
\1)      - seguida do que foi capturado no grupo 1

Example in the code:

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

console.log(idsEncontrados);

However, just as @Andersoncarloswoss mentioned, it’s an easy logic to implement directly into Javascript using the filter.

See the related question: Remove repeated elements within a javascript array

  • Thank you @Isac! Your regular expression solution worked perfectly. I think it’s easier to use regular expression, although the @Andersoncarloswoss suggestion is also a great alternative.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.