I have to remove a set of lines that start with a marker and end with another marker.
I want to find all such pieces of text and remove them using regex. The problem is, regex only matches one line at a time. How should I proceed?
I have to remove a set of lines that start with a marker and
Share
In most regex parsers, you can add a
sto the end as a “dotall” modifier. This will make.match anything, including newlines (which it normally does not match).But the dotall modifier does not exist in javascript. Instead, you have a “pseudo-dotall” modifier by using a predefined character class and its negation — collectively these two things will match anything, including a newline. The canonical example is
[\s\S](match anything that is whitespace or anything this is not whitespace = match anything). But any character class and its negation will do (e.g.[\d\D]will also work).So in your case, if your start token is
Sand your end token isEyou can do this:Two notes: I am using the
gor global modifier to replace all instances. And in[\s\S]*?, the?means “match the shortest sequence” (non-greedy). That way it really will be instances of delimited tokens rather than treating all the stuff between the first begin token and last end token as a single token.