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

259
Visualizações
Regular Expressions: Using multiple lookbehinds to format blocks of JSON

N.B: This question is being asked purely for learning purposes. I am well aware that the specific problem posed can be trivially solved in any modern code editor.

I love the power of regular expressions, but have never quite understood how to use their more-advanced features, especially lookarounds. After two hours of SO searching and Googling, plus using regexr.com, I have come up with the following:

// Search regex: (?<=\[\n *\{\n)(?<= {4})(.*\n)*
// Replace regex: [{\n$&]

// Should take the following JSON object array:

[
    {
        "prop1": val1,
        "prop2": val2,
        // ...arbitrary number of props
    },
    // ...arbitrary number of objects matching the above structure
]

And format it like so:

[{ // first object's opening brace adjacent to opening bracket
    // ...first object's props
}, {
    // ...other objects' props
}] // last object's closing brace adjacent to closing bracket

The second lookbehind is an attempt to deindent each prop line, and the lines that close each object and open the next one. But it seems to break the whole thing.

Without it I get almost a perfect result, but the lines are not deindented and the newline after the final object's closing brace is also erroneously matched, like so (see the link for a more complete example):

[{
        "prop1": val1,
        "prop2: val2
    }, {
        "prop1": val1,
        "prop2: val2
    }
]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

For your specific input, you can delete all matches of

/^    |(?<=\[)[ \n]*(?=\{)|(?<=\})[ \n]*(?=\])/gm

See RegExr link. Alternatively, replace all matches of

/^    |(\[)[ \n]*(\{)|(\})[ \n]*(\])/gm

by $1$2$3$4.

But that only works if the input is formatted exactly as shown in your question, and if the strings (keys or values) do not contain {. "Power of regular expressions" is a good keyword, as classical regexes lack the power to process arbitrarily nested braces. They are not designed to process Type II grammars like JSON.

about 4 years ago · Juan Pablo Isaza 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