-3

i need a regex to check following conditions on a string :-

1) it contains only numbers (0-9) 2) string must contain three unique digits 3) there must be no white space in the string 4) and length of the string must be of 10.

valid strings example "1234567890" "1122557890" "7878787808"

invalid strings :- "7878787878" "1111122222"

Flexsin Tech
  • 207
  • 3
  • 10
  • 1
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [tour] and [ask] – Luca Kiebel May 03 '18 at 13:28
  • Share what you tried and I'll be glad to help – Savandy May 03 '18 at 13:29
  • i have used the following regex ^(\d)\1*+(?!.*\1)(\d)\2*+(\d)\3*+$ it is giiving me result for string which contain only 3unique digits like "123" ,"11222333" but not according to my need – Flexsin Tech May 03 '18 at 13:32
  • The white spaces, the numbers, and the length are easy to do with regex. Any reason why you can't check the uniqueness of the digits outside of the regex? – Juan May 03 '18 at 13:39
  • @FlexsinTech Could you add the regex you have tried to your question? – The fourth bird May 03 '18 at 14:22

1 Answers1

0

What you might do is match 10 digits ^[0-9]{10}$ from the begining ^ until the end $ of the string and first test if that succeeds.

If that is the case you could get only the unique values from the string and if that count is equal or greater than 3 you have your match.

There are multiple ways to remove the duplicate values from your array. For this example I have used a method from this page.

let strings = [
  "1234567890",
  "1122557890",
  "7878787808",
  "7878787878",
  "1111122222"
];
let pattern = /^[0-9]{10}$/;

strings.forEach((s) => {
  if (pattern.test(s)) {
    let a = s.split("").filter(function(x, i, a) {
      return a.indexOf(x) === i;
    });
    if (a.length >= 3) {
      console.log("Valid: " + s);
    }
  }
});
The fourth bird
  • 154,723
  • 16
  • 55
  • 70