From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../global_objects/regexp/exec/index.html | 230 +++++++++++++++++++++ 1 file changed, 230 insertions(+) create mode 100644 files/pt-br/web/javascript/reference/global_objects/regexp/exec/index.html (limited to 'files/pt-br/web/javascript/reference/global_objects/regexp/exec') diff --git a/files/pt-br/web/javascript/reference/global_objects/regexp/exec/index.html b/files/pt-br/web/javascript/reference/global_objects/regexp/exec/index.html new file mode 100644 index 0000000000..b5f722a55d --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/regexp/exec/index.html @@ -0,0 +1,230 @@ +--- +title: RegExp.prototype.exec() +slug: Web/JavaScript/Reference/Global_Objects/RegExp/exec +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/exec +--- +
{{JSRef}}
+ +

O método exec() executa a busca por um padrão em uma determinada string. Retorna um array, ou {{jsxref("null")}}.

+ +

Se você está precisa somente de um retorno verdadeiro/falso, use o método {{jsxref("RegExp.prototype.test()")}} ou {{jsxref("String.prototype.search()")}}.

+ +

Sintaxe

+ +
regexObj.exec(string)
+ +

Parâmetros

+ +
+
string
+
A string para comparar com a expressão regular
+
+ +

Valor retornado

+ +

Se a combinação acontecer, o método exec() o método retorna um array e atualiza as propriedades do objeto da expressão regular. Esse array retornado possui o texto combinado como primeiro item e depois um item para cada captura contendo o respectivo texto.

+ +

Se falhar, o retorno do método exec() será {{jsxref("null")}}.

+ +

Descrição

+ +

Considere o exemplo abaixo:

+ +
// Encontra combinações "quick brown" seguido de "jumps", ignorando caracteres entre eles
+// Relembra "brown" e "jumps"
+// Ignora caixa (maiúsculo e minúsculo)
+var re = /quick\s(brown).+?(jumps)/ig;
+var result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog');
+
+ +

A tabela a seguir provê os resultados do script:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ObjetoPropriedade/ÍndiceDescriçãoExemplo
result[0]A string completa dos caracteres encontradosQuick Brown Fox Jumps
[1], ...[n ]As combinações de substrings parametrizadas encontradas, se existir. A quantidade de possíveis substrings parametrizadas é ilimitado.[1] = Brown
+ [2] = Jumps
index +

O índice base 0 do valor encontrado na string.

+
4
inputString originalThe Quick Brown Fox Jumps Over The Lazy Dog
relastIndexO índice que começa a próxima combinação encontrada. Quando "g" não é definido, este valor será sempre 0.25
ignoreCaseIndica se a flag "i" foi usada para ignorar caixa alta/baixa.true
globalIndica se a flag "g" foi usada para encontrar combinações de forma global.true
multilineIndica se a flag "m" foi usada para pesquisar em strings de diversas linhas.false
sourceTexto do padrão.quick\s(brown).+?(jumps)
+ +

Exemplos

+ +

Procurando combinações sucessivas

+ +

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's {{jsxref("RegExp.lastIndex", "lastIndex")}} property ({{jsxref("RegExp.prototype.test()", "test()")}} will also advance the {{jsxref("RegExp.lastIndex", "lastIndex")}} property). For example, assume you have this script:

+ +
var myRe = /ab*/g;
+var str = 'abbcdefabh';
+var myArray;
+while ((myArray = myRe.exec(str)) !== null) {
+  var msg = 'Found ' + myArray[0] + '. ';
+  msg += 'Next match starts at ' + myRe.lastIndex;
+  console.log(msg);
+}
+
+ +

This script displays the following text:

+ +
Found abb. Next match starts at 3
+Found ab. Next match starts at 9
+
+ +

Note: Do not place the regular expression literal (or {{jsxref("RegExp")}} constructor) within the while condition or it will create an infinite loop if there is a match due to the {{jsxref("RegExp.lastIndex", "lastIndex")}} property being reset upon each iteration. Also be sure that the global flag is set or a loop will occur here also.

+ +

Usando exec() com RegExp literais

+ +

You can also use exec() without creating a {{jsxref("RegExp")}} object:

+ +
var matches = /(hello \S+)/.exec('This is a hello world!');
+console.log(matches[1]);
+
+ +

This will log a message containing 'hello world!'.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.10.6.21', 'RegExp.exec')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-regexp.prototype.exec', 'RegExp.exec')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-regexp.prototype.exec', 'RegExp.exec')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + -- cgit v1.2.3-54-g00ecf