Regular expressions and text guides
Greedy and lazy regex: match delimiters deliberately
Compare greedy, lazy and negated-character patterns without using regex as a nested-format parser.
See how far a greedy match goes
A greedy quantifier first tries to consume as much as possible while allowing the remaining pattern to match.
With two bracketed values, a dot-star pattern can consume both as one match. Check the complete match rather than only whether it exists.
'[one][two]'.match(/\[.*\]/g) → ['[one][two]']Make the quantifier lazy
Adding a question mark makes the quantifier prefer fewer characters. It still expands if the rest of the pattern cannot match.
For a simple flat bracket format, the lazy version finds each pair separately in this fixture.
'[one][two]'.match(/\[.*?\]/g) → ['[one]','[two]']Express forbidden delimiters directly
A negated character class can state that content must not contain the closing delimiter. This often describes the flat grammar more clearly.
If line breaks are disallowed, exclude them explicitly too; dot behavior and character-class behavior are different.
/\[[^\]\r\n]*\]/gKnow where the flat grammar ends
Escaped delimiters and nested brackets need additional rules. A lazy quantifier does not understand nesting or quoted strings.
Use the format's parser for structured languages. Test an unmatched opener, an empty pair and a forbidden newline before deploying a flat matcher.