www.webdeveloper.com
Results 1 to 3 of 3

Thread: regular expression for equal number of two chars

  1. #1
    Join Date
    Feb 2011
    Posts
    90

    regular expression for equal number of two chars

    how can I write regular expression that accept any string that has equal number of 'a' and 'b'?

  2. #2
    Join Date
    Feb 2006
    Posts
    2,927
    It is easy with 2 expressions-

    Code:
    var equalAandB=(str.match(/a/g) || []).length === (str.match(/b/g) || []).length;
    Last edited by mrhoo; 06-08-2012 at 07:10 AM.

  3. #3
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,277
    it's too easy to build a function with a variant...
    Code:
    String.prototype.asMuchAs=function(a,b){return this.replace(new RegExp(a,'ig'),'').length==this.replace(new RegExp(b,"ig"),'').length}
    // Test
    var str="NATO Apologizes for Deaths in Airstrike, Explosion Hits Police Bus in Pakistan, Cameron to Appear at Hacking Inquiry".split(',');
    for (var i in str) alert(str[i]+' '+str[i].asMuchAs('a','i'));

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles