Put in array strings according to a regular expression

Asked

Viewed 322 times

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?

3 answers

1


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

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

jsFiddle: http://jsfiddle.net/3sc6vvoj/

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

  • And if I need a word with an accent?

  • 1

    @Joaopaulo everything that is inside [] You want to "catch" right? In that case you can have /(\[.*?\])/g

1

You can do it like 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]"]

1

Another expression that can be used is /\[(?:.*?)\]/ that will match anything 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

Browser other questions tagged

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