RegEx只有在特定HTML元素中出现时才匹配字符串

tho*_*rad 4 html regex visual-studio-2013

我试图在Visual Studio 2013项目中找到某些代码部分.我正在使用RegEx搜索功能(我在"搜索选项"下选中"使用正则表达式").

更具体地说,我正在尝试找到位于开始和结束脚本标记之间的字符串"findthis"(不带引号).RegEx应该能够匹配字符串多行.

例:

<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>
Run Code Online (Sandbox Code Playgroud)

到目前为止我尝试的是以下((?s)启用多行):

(?s)\<script\>.*?(findthis).*?\</script\>
Run Code Online (Sandbox Code Playgroud)

这里的问题是,当脚本结束标记出现时,它不会停止搜索"findthis".这就是为什么在Visual Studio 2013中,它还会在搜索结果中的正文开头标记之后显示脚本元素.

任何人都可以帮助我摆脱这个RegEx地狱吗?

Wik*_*żew 5

您可以使用此正则表达式来避免匹配<script>标记:

<script>((?!</?script>).)*(findthis)((?!</?script>).)*</script>
Run Code Online (Sandbox Code Playgroud)

或者,更有效的原子分组:

<script>(?>(?!</?script>).)*(findthis)(?>(?!</?script>).)*</script>
Run Code Online (Sandbox Code Playgroud)

我假设我们不想在开头<script>之间匹配,也不想在两者之间关闭标签,所以,我在/?里面使用(?>(?!</?script>).)*,只是为了避免任何其他格式错误的代码.我再次重复它(findthis),以便我们只匹配未被任何一个<script>或后面跟随的字符</script>.

在Expresso中进行了测试,略微修改了输入(我添加<>在任何地方模拟损坏):

在此输入图像描述