I'm trying to find certain code portions in a Visual Studio 2013 project. I'm using the RegEx search function for that (I check "Use Regular Expressions" under Search Options).
More specificly, I'm trying to find the string "findthis" (without quotes) that lies between an opening and a closing script tag. The RegEx should be able to match the string multi-line.
Example:
<html>
<head>
<script>
var x = 1;
if (x < 1) {
x = 100;
}
var y = 'findthis'; // Should be matched
</script>
</head>
<body>
<script>
var a = 2;
</script>
<h1>Welcome!</h1>
<p>This findthis here should not be matched.</p>
<script>
var b = 'findthis too'; // Should be matched, too.
</script>
<div>
<p>This findthis should not be matched neither.</p>
</div>
</body>
</html>
What I've tried so far is the following (the (?s)
enables multi-line):
(?s)\<script\>.*?(findthis).*?\</script\>
The problem here is that it does not stop searching for "findthis" when a script end tag occurs. That's why, in Visual Studio 2013, it also shows the script element right after the body opening tag in the search results.
Can anyone help me out of this RegEx hell?
You can use this regex to avoid matching <script>
tags:
<script>((?!</?script>).)*(findthis)((?!</?script>).)*</script>
Or, a more effecient one with atomic groupings:
<script>(?>(?!</?script>).)*(findthis)(?>(?!</?script>).)*</script>
I am assuming we do not want to match neither opening, nor closing <script>
tags in between, so, I am using /?
inside (?>(?!</?script>).)*
, just to avoid any other malformed code. I repeat it after (findthis)
again, so that we only match characters that are not followed by either <script>
or </script>
.
Tested in Expresso with a slightly modified input (I added <
and >
everywhere to simulate corruptions):
Built off of @Aaron's answer:
\<script\>(?:[^<]|<(?!\/script>))*?(findthis).*?\<\/script\>
Debuggex Demo
So you can see I do (?:[^<]|<(?!\/script>))
to say "match anything that isn't a <
, or a <
that isn't followed by /script>
".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With