Put in array strings according to a regular expression

2

I would like to make an array containing strings in this format:

[Texto com acento espaço e números 99]

Example, if I have this string:

var texto = "Eu quero comprar [qtdOvos] e [qtdFrutas] somando o total de [totalCompras]";

I need to mount the following array:

var arrayStrings = ["[qtdOvos]", "[qtdFrutas]", "[totalCompras]";

Is there any way to do this through regular expression?

    
asked by anonymous 30.01.2015 / 21:03

3 answers

1

Yes, it is possible. You can use: .match(/(\[\w+\])/g) .

In this case you have to "escape" the [ because they are reserved in Regex. You create a capturing group with () , you use \w+ to say that it is a letter or number and g to say that it is recurring.

jsFiddle: link

If you want to "catch" everything within [] more comprehensively you can use /(\[.*?\])/g .

    
30.01.2015 / 21:06
1

You can do this:

var texto = "Eu quero comprar [qtdOvos] e [qtdFrutas] somando o total de [totalCompras]";
var arrayStrings = texto.match(/\[[A-Za-z0-9]+\]/gi);

arrayStrings will contain exactly what you want:

["[qtdOvos]", "[qtdFrutas]", "[totalCompras]"]
    
30.01.2015 / 21:07
1

Another expression that can be used is /\[(?:.*?)\]/ which will correspond to everything that is between [ and ] .

var texto = "Eu quero comprar [qtdOvós] e [qtdFrutâs] somando o total de [total Comprãs]";    
var array = texto.match(/\[(?:.*?)\]/g);

// [qtdOvós],[qtdFrutâs],[total Comprãs]

DEMO

    
30.01.2015 / 21:16