Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

260
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!