Home > Software engineering >  Is it possible to select only non repeated number using Regex
Is it possible to select only non repeated number using Regex

Time:12-21

Here is my number 1123223 In this number I find the not repetitive at 123 after and before all are under the repetition. how to select only 123 using regex is it possible?

I tried it ^(\d)(?!\1{7})\d{7}$ - but not works.

I need to set my input field validation length according to the value I and it's length from server side data.

CodePudding user response:

It appears you can try the following:

\d(?:(?<=0)1|(?<=1)2|(?<=2)3|(?<=3)4|(?<=4)5|(?<=5)6|(?<=6)7|(?<=7)8|(?<=8)9)*

See an online demo

You can apply this pattern to retrieve all matches, then sort the array by length and retrieve the longest match:

const strs = ['12341234','1123223','1112356789','123456789','789123'];
strs.forEach(str => {
    console.log(str.match(/\d(?:(?<=0)1|(?<=1)2|(?<=2)3|(?<=3)4|(?<=4)5|(?<=5)6|(?<=6)7|(?<=7)8|(?<=8)9)*/g).sort((a, b) => b.length - a.length)[0])
})

  • Related