How to retrieve the number of characters via regular expression?

7

How to know the amount of repeated characters (example: Goi a b a = 2 letters a ) , consecutive characters (sequence of letters abc .. ) and consecutive numbers (example: 12345 .. ) within a word, using regular expression? Is this possible?

    
asked by anonymous 02.02.2015 / 17:37

2 answers

2

With regular expressions it should not be possible to do this as quoted in response from Miguel Angelo, however, through a loop you can get the number of occurrences of the characters and store them in a associative array .

var str = "Goiaba";
var ocorrencias = {};

for(var i = 0; i < str.length; i++) {
    var n = str[i];
    ocorrencias[n] = ocorrencias[n] ? ocorrencias[n] + 1 : 1;
}    
console.log(ocorrencias); // {G=1, o=1, i=1, a=2, b=1}

DEMO

To make it more beautiful and organized do this in one function:

function retornarOcorrencias(str){
    var ocorrencias = {};
    for(var i = 0; i < str.length; i++){
        var n = str[i];
        ocorrencias[n] = ocorrencias[n] ? ocorrencias[n] + 1: 1;
    }
    return ocorrencias;
}

var str = 'Goiaba';
var num = '001549954607410';

var strItens = retornarOcorrencias(str); 
var numItens = retornarOcorrencias(num); 

console.log(strItens); // {G=1, o=1, i=1, a=2, b=1}
console.log(numItens); // {0=4, 1=2, 4=3, 5=2, 6=1, 7=1, 9=2}

DEMO

To check the number of occurrences of a particular character:

console.log(strItens['a']); // 2

In the answers below shows how to do this in PHP:

03.02.2015 / 01:34
1

I think there is no way to do this with RegExp .

Go to a JavaScript to detect duplicate points in your string. See if it suits you:

function DetectarRepeticoes(str) {
    var obj = {};
    for (var itL = 1; itL <= str.length; itL++) {
        for (var itS = 0; itS <= str.length - itL; itS++) {
            var seq = str.substr(itS, itL);
            obj[seq] = obj.hasOwnProperty(seq) ? obj[seq]+1 : 1;
        }
    }
    var res = {};
    for (var k in obj) {
        if (obj.hasOwnProperty(k) && obj[k]>1)
            res[k] = obj[k];
    }
    return res;
}

Example usage:

DetectarRepeticoes("Miguel Angelo Santos Bicudo");

Return:

{
    " ": 3,
    e:   2,
    el:  2,
    g:   2,
    i:   2,
    l:   2,
    n:   2,
    o:   3,
    u:   2
}

Note: this method is order of n 2 , where n is the number of characters in the string ... so it is not very efficient. But if it is to use with small strings it is acceptable ... up to 1000 characters I think it still looks good in most cases.

    
02.02.2015 / 19:05