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

时间:2015-04-10 09:48:06

标签: 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>

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

(?s)\<script\>.*?(findthis).*?\</script\>

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

任何人都可以帮我解决这个RegEx地狱吗?

3 个答案:

答案 0 :(得分:5)

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

<script>((?!</?script>).)*(findthis)((?!</?script>).)*</script>

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

<script>(?>(?!</?script>).)*(findthis)(?>(?!</?script>).)*</script>

我假设我们不希望既不匹配也不匹配两者之间的<script>标记,因此,我在/?内使用(?>(?!</?script>).)*,以避免任何其他格式错误的代码。我再次在(findthis)之后重复此操作,以便我们只匹配<script></script>之后未跟随的字符。

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

enter image description here

答案 1 :(得分:2)

基于@Aaron的回答:

\<script\>(?:[^<]|<(?!\/script>))*?(findthis).*?\<\/script\>

Regular expression visualization

Debuggex Demo

因此,您可以看到我(?:[^<]|<(?!\/script>))“匹配任何非<<未跟/script>的内容}“

答案 2 :(得分:1)

也许这有效

(?s)\<script\>[^<]*?(findthis).*?\</script\>

[^<]*?部分会避免在匹配findthis之前匹配另一个标记。

请参阅https://www.regex101.com/r/pV7iY6/1