Why does not my regEx work as expected?

2

I really have difficulty setting up regular expressions, mainly for varying their behavior in each language. I'm translating a Java code into JS, in which the regular expression is /(\d{1,4}|\*)\s*[xX]\s*(\d{1,4}|\*)/ , so I understand it captures any number (size from 1 to 4 characters) that have at least the X or x separating from another set of numbers.
My question is: Why can not I capture "1024x768 px until 1920x1080" so I can match also in "1920x1080"?

JS

function process(val) {
    if (val != null) {
        val = val.replace("X", "x");
        val = val.replace(/ /g, "");
        const DIMENSAO_UNIT = "px";
        const DIMENSAO_PATTERN = /(\d{1,4}|\*)\s*[xX]\s*(\d{1,4}|\*)/;
        var normalizado = val.trim().toLowerCase().replace(DIMENSAO_UNIT, "");
        var valores = [];
        var out = "";
        if (DIMENSAO_PATTERN.test(val)) {
            var getNumbers = val.match(DIMENSAO_PATTERN);
            var i = 0;
            for (i = 0; i < getNumbers.length; i++) {
                valores.push(getNumbers[i]);
            }
        }
        if(val == ""){
            return "";
        }
        if (normalizado.indexOf("superior") > -1) {
            return valores[0] + DIMENSAO_UNIT + " ou superior";
        } else if (normalizado.indexOf("até") > -1) {
            if (valores.length == 1) {
                out = "até " + valores[0];
            } else {
                out = valores[0] + " até " + valores[1];
            }
        } else if (normalizado.indexOf("ou") > -1 || normalizado.indexOf("/") > -1) {
            out = valores[0];
            var j = 0;
            for (j = 1; j < valores.length; j++) {
                out = "/" + valores[j];
            }
        } else {
            if (valores.length > 0) {
                out = valores[0];
            }
        }
        if (out !== null || out !== "") {
            return out + DIMENSAO_UNIT;
        }
        return "";
    }
    return null;
}


regEx test

** UPDATE: I just needed to add the global (g): /(\d{1,4}|\*)\s*[xX]\s*(\d{1,4}|\*)/g but leave open p explanations

    
asked by anonymous 30.04.2015 / 13:46

1 answer

2

The problem is not in regex , as you well understood, but in the regexes handling JavaScript functions. The match function of type String returns:

  • The first marriage found, along with its catch groups, if the regular expression does not have the flag g ;
  • All marriages found, if regex has the flag g . In this case, the capture groups are ignored.

Example:

var str = "abracadabra";

var regex1 = /a(.)/;
var regex2 = /a(.)/g;

var match1 = str.match(regex1);
var match2 = str.match(regex2);

document.body.innerHTML += "<p>" + JSON.stringify(match1) + "</p>";
document.body.innerHTML += "<p>" + JSON.stringify(match2) + "</p>";
    
30.04.2015 / 14:00