Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

254
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda