Re: Regex for outside of bracketsby mr_mischief (Monsignor)
|on Jul 13, 2018 at 22:03 UTC||Need Help??|
Are you sure you want a match, and that you can only use a single regex? I have bad news... a regular language has no context. However, a regular expression and another tool or handful of tools can easily get you there. Take, for example, the substitution operator, a counter with a loop and some more regexes, or a regex match and a split on the match... Of course, feel free to use Text::Balanced as atcroft suggests or use some other toolset built for the level of the problem you're trying to solve. Regexes will only solve a subproblem of your problem.
Here's the data file for the following examples.
Now here's the first example, using the substitution operator.:
The above code produces the following output by substituting 0 characters in place of any pair of parentheses with anything between them. As written, it eliminates matched pairs and their contents but will also eliminate an extra closing parenthesis and will include in the output an opened but not closed parenthetical.:
Or if prefer to preserve whitespace as it was, set $cleanup to 0
This next example produces mostly the same output as the ącleanup = 0 version of the above. It does so by counting nesting level of the parentheses after splitting the string into an array of characters. It then appends to the output string if the nesting level is 0 (outside of any pairs of parentheses). This one will produce its last output before a hanging opened and unclosed pair. It will, as written, also not include in the output negative nesting levels (text trailing an extra close unmatched by an open).
Or if you want to feed the match from one regex match into a split on that match...
The above works because we know what we want to eliminate, which is a good use for split. In this particular case, we don't have a fixed regex against which to split, but we know how to match what we don't want. This solution captures that unwanted part, quotes it with \Q and \E, joins any multiples with the regex alternation (pipe, or '|'), then uses split and join to leave what's left of the string as a single string. This as written will only eliminate matched pairs and their contents. This is basically emulating the substitution operator. One's intuition may be that since it's a more detailed treatment it'll be faster. However, we're more Perl here, and the substitution operator is highly optimized. I don't know without benchmarking by how much, but I'm betting the example with the s/// is faster.
The second example above is fairly easy to tweak to give the sort of error messages you might expect out of a lexer, since it is kind of a degenerative case of one.