How to select with regex?

Asked

Viewed 168 times

3

I am trying to format text of the following type

123,345,234   //tem que ficar 123345,234
abc,def,adf   //tem que ficar abcdef,adf
123,345,678,abc,qualquer,coisa    //tem que ficar 123345678abcqualquer,coisa

I need to remove all comma, except the last, as I do this with regular expression in javascript?

2 answers

3

You can do this only with javascript:

function arranjar(str){
    var partes = str.split(',');
    var ultima = partes.pop();
    return [partes.join(''), ultima].join(',');
}
arranjar('123,345,678,abc,qualquer,coisa') // dá "123345678abcqualquer,coisa"

To do this with regex is no longer simple. But an example would be like this:

function arranjarComRegex(str){
    var partes = str.match(/(.*),(.*)/);
    var string = partes[1].replace(/,/g, '');
    return string + ',' + partes[2];
}

In this case the regex (.*),(.*) captures two groups. On the first catch '123,345,678,abc,qualquer' where you need to remove the commas with .replace(/,/g, '') and the second capture group gets the last word, which then needs to join back in the string with string + ',' + partes[2].

  • is that actually, I wanted to know more on how to do this with regex

  • @Lai32290 ok, I’ll add an example with regex.

3


Use the regex /,(?=[^,]*,)/g and the method replace:

var a = "123,345,234";   //tem que ficar 123345,234
var b = "abc,def,adf";   //tem que ficar abcdef,adf
var c = "123,345,678,abc,qualquer,coisa";    //tem que ficar 123345678abcqualquer,coisa

var a2 = a.replace(/,(?=[^,]*,)/g, "");
var b2 = b.replace(/,(?=[^,]*,)/g, "");
var c2 = c.replace(/,(?=[^,]*,)/g, "");

document.write(a2 + "<br/>");
document.write(b2 + "<br/>");
document.write(c2);

  • That’s exactly what I need!! can you explain to me what the part means (?= ) ?

  • 1

    This part indicates a condition for the comma to be considered. The condition I used is that there must be another comma after the term in question. Therefore, they are only considered in substitution, commas that after it appears another comma.

  • 1

    I use the regex101.com to test regexes, take a look that is worth.

  • Thank you very much!! learned!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.