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 4 of 4
  1. #1
    New Coder
    Join Date
    Jun 2011
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Regular Expressions - Matching two strings, order doesn't matter

    When given two strings:

    String A:

    Code:
    25,97,84,10,341,0,0,310
    String B:

    Code:
    97,25,84,0,310,0,10,341
    They both contain the same numbers just in different orders.

    How can I use regular expressions or another method to determine if these strings match disregarding order?

  2. #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Location
    Here
    Posts
    3,576
    Thanks
    58
    Thanked 649 Times in 644 Posts
    you could turn them into arrays, sort them then compare them:

    Code:
    <script type = "text/javascript">
    var strA="25,97,84,10,341,0,0,310"
    var strB="97,25,84,0,310,0,10,341"
    
    var outA=strA.split(",").sort().toString()
    var outB=strB.split(",").sort().toString()
    
    if (outA==outB){
    alert("match!")
    } else{
    alert("no match!")
    }
    
    </script>

  3. Users who have thanked xelawho for this post:

    ndm250 (03-24-2013)

  4. #3
    New Coder
    Join Date
    Jun 2011
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by xelawho View Post
    you could turn them into arrays, sort them then compare them:

    Code:
    <script type = "text/javascript">
    var strA="25,97,84,10,341,0,0,310"
    var strB="97,25,84,0,310,0,10,341"
    
    var outA=strA.split(",").sort().toString()
    var outB=strB.split(",").sort().toString()
    
    if (outA==outB){
    alert("match!")
    } else{
    alert("no match!")
    }
    
    </script>
    This is perfect. Thanks for the quick response.

  5. #4
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    I thought maybe using the recent every method you could do this:
    Code:
    <script type="text/javascript">
    
    arrA = [ 3, 2, 1 ], arrB = [ 1, 2, 3 ];
    
    Array.prototype.compareDimension = function( other )
    {
      var me = this;
      
      return this.every( function(a){ return other.indexOf( a ) != -1; } ) &&
             other.every( function(a){ return me.indexOf( a ) != -1; } )
    }
    
    
    alert( arrA.compareDimension( arrB ) );
    
    </script>
    Last edited by Logic Ali; 03-24-2013 at 02:42 AM.


 

Posting Permissions

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