Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
Trying to match array index pattern in string using Regex

I'm using regex to get the indices of variables accessing pattern represented as string, for example:

string = "test[2][56].var1[4]"

The regex match result in the groups 2, 56, 4 captured.

matchGroups = ["2", "56", "4"]

The regex below works.

\[([^\.\]]+)\]

But I can't allow cases like:

"test.[3].var1" or "test[3]/"

I tried to limit the characters allowed before and after each group using the regex below:

[\]a-zA-Z0-9]\[([^\.\]]+)\]([\[a-zA-Z0-9])?

But some cases stopped working like the case "test[0].var7[3][4]"(4 is not captured).

I need help to make this work with all cases again(cases are in the link below).

https://regex101.com/r/mOgOHn/2

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

I would replace the string, then do matching

Replace Regex:

/.*?\[(\d+)\].*?/

Replace the string where any number between brackets is replaced by a number followed by ,

Match Regex:

/\d+(?=,)/

Look ahead positive; which Find any number followed by ,

const captureNumber = str => str.replace(/.*?\[(\d+)\].*?/g, "$1,").match(/\d+(?=,)/g)

console.log(captureNumber("test[0].var7[3][4]")); //[ "0", "3", "4" ]
console.log(captureNumber("test[3]/")); //[ "3" ] 
console.log(captureNumber("test.[3].var1")); //[ "3" ] 
console.log(captureNumber("test[2][56].var1[4]")); //[ "2", "56", "4" ]

about 4 years ago · Santiago Trujillo Relatório

0

the simplest would be to use a regexp using a positive lookbehind and a positive lookahead. To this, you can add safety on spaces in case you have a case like "test[ 2 ][ 56 ].var1[ 4 ]", to which a .trim() method string must be applied. Here is a snippet illustrating this:

const getIndex = str => str.match(/(?<=\[) *\d+ *(?=\])/g).map(val => val.trim());

console.log(getIndex("test[0].var7[3][4]")); //[ "0", "3", "4" ]
console.log(getIndex("test[3]/")); //[ "3" ]
console.log(getIndex("test.[3].var1")); //[ "3" ]
console.log(getIndex("test[2 ][   56   ].var1[4 ]")); //[ "2", "56", "4" ]

Good luck !

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda