Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Sep 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    regex validation

    Hi all,
    can anyone give an example of regex which should not accept duplicate numbers separated with comma.
    it should accept numbers like 1,2 and it should not repeat duplicates like 1,2,3,1,2,3
    and also the number should terminate with a number like 1,2,3 and it should not terminate with , like 1,2, please help me

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,917
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    I don't think that a single regex can do this. You need something like:-

    Code:
    <html>
    <head>
    </head>
    
    <body>
    
    <script type = "text/javascript">
    
    var val = "1,2,3,1,2,3,1,5,3,8,";
    val = val.replace(/\,$/,"");  // strip final comma if any
    sval = val.split(","); //split string into an array
    
    for (var i = 0; i<sval.length; i++) {
    for (var j = i+1; j<sval.length; j++) {
    
    if (i!=j)  {
    if ((sval[i] == sval[j]) && sval[i] !="") {
    alert ("The value " + sval[i] + " array index " + i + " is duplicated at array index " + j);
    sval[j] = "";  // delete duplicates
    }
    }
    
    }
    }
    
    // ---------------------------------------------------------
    
    var sval2 = [];
    var j=0;
    for (var i = 0; i<sval.length; i++) {
    if (sval[i] !=  "" ) {  // remove blanks (were duplicates)  from the array
    sval2[j] = sval[i];
    j++;
    }
    }
    
    var final  = sval2.join(",");
    alert (final);
    
    </script>
    
    </body>
    </html>
    Quizmaster: The Spanish Steps and the Colliseum lie in which Italian city?
    Contestant: Athens.
    Last edited by Philip M; 09-24-2012 at 01:03 PM. Reason: Revised

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •