Reputation: 8648
I am trying to develop a quick hack in SublimeText2 (not ideal, I know):
I have this (frequent) code in my markup:
{% url '
someURL ' %}
How can I use regex to remove the line breaks such that I have {% url 'someURL '%}
I have succeeded in selecting eveything between the brackets:
\{\%[\s\S]*?\%\}
However, I can't figure out how to select only the linebreaks \n
and double spaces within it.
Upvotes: 1
Views: 2503
Reputation: 89629
You can use this pattern:
(?:\G(?!\A)|\{%)[^%\r\n]*\K(?:\r?\n)+(?=[^%]*%\})
The replacement is an empty string.
This pattern ensure that you are always between tags {%
and %}
using the \G
anchor that matches the position at the end of the previous match.
The \K
removes all that have been matched on the left from the match result. So only the CRLF or LF is removed.
This pattern can be improved if you want to allow %
characters between tags:
(?:\G(?!\A)|\{%)(?:[^%\r\n]|%(?!\}))*\K(?:\r?\n)+(?=(?:[^%]|%(?!\}))*%\})
or more efficient (if it is possible with sublimetext):
(?:\G(?!\A)|\{%)(?>[^%\r\n]+|%+(?!\}))*\K(?:\r?\n)+(?=(?>[^%]+|%+(?!\}))*%\})
a little shorter (if sublimetext regex engine is smart enough):
(?:\G(?!\A)|{%)(?>[^%\r\n]+|%+(?!}))*\K\R+(?=(?>[^%]+|%+(?!}))*%})
Note: if you are sure that tags are always balanced, you can remove the last lookahead (but this way is less safe):
(?:\G(?!\A)|{%)(?>[^%\r\n]+|%+(?!}))*\K\R+
Upvotes: 1
Reputation: 174826
Use the below regex and then replace the match with a single space.
(?s)\s+(?=(?:(?!%}|\{%).)*%\})
Explanation:
(?s) set flags for this block (with . matching
\n) (case-sensitive) (with ^ and $
matching normally) (matching whitespace
and # normally)
\s+ whitespace (\n, \r, \t, \f, and " ") (1 or
more times)
(?= look ahead to see if there is:
(?: group, but do not capture (0 or more
times):
(?! look ahead to see if there is not:
%} '%}'
| OR
\{ '{'
% '%'
) end of look-ahead
. any character
)* end of grouping
% '%'
\} '}'
) end of look-ahead
Upvotes: 3
Reputation: 2067
(\{%.*)\n\s*(.*%\})
With replace string \1\2
will change
{% url '
someURL ' %}
to {% url 'someURL ' %}
Upvotes: 0