In a multi-line file I want to check that all lines match one or more complex patterns (which may each cover multiple lines).
I can make this work just fine with this RegEx
\A(patternA\n|patternB\n)*\z
(For some languages it works with \Z instead of \z)
It will match:
patternA
patternB
patternA
and will reject
patternA
patternC
patternB
But it does not work in JavaScript (where I need to execute the test) because JavaScript RegEx apparently does not support the anchors \A (start of file) or \z (end of file). And if those anchors are left off then I just get back a set of matches (the first and third lines in my second example above), without the information that there are also non-matches.
At the moment, the only thing I can think of is to run the RegEx check without those two anchors, and then check that the sum of the length of all the matches equals the length of the overall text, but this seems rather clunky.
Is there a simple/elegant way to implement this check in JavaScript RegEx?
I now think the best solution may be to invert logic so that it searches for anything that does not match the required patterns, and passes the check if no match is found. The following RegEx, running under JavaScript, for example, matches the second example from my original post and not the first:
^(?!patternA$|patternB$|$)
The last option ($) is needed as otherwise it always matches the (empty) line following the last newline.
If the individual patterns are complex, it may be both easier on the regex engine and simpler to understand to write imperative code that loops through each of the lines and checks for each of the patterns in order.
This will let each of the patterns stay one regex. They do not have to be baked into the "whole file" pattern when one is updated, added or removed. The different patterns can also use different regex flags and so on.