作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试在 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 hell ?
最佳答案
您可以使用此正则表达式来避免匹配 <script>
标签:
<script>((?!</?script>).)*(findthis)((?!</?script>).)*</script>
或者,更高效的原子分组:
<script>(?>(?!</?script>).)*(findthis)(?>(?!</?script>).)*</script>
我假设我们不想匹配开盘和闭盘 <script>
之间的标签,所以,我正在使用 /?
里面(?>(?!</?script>).)*
,只是为了避免任何其他格式错误的代码。我在 (findthis)
之后重复再次,以便我们只匹配后面没有 <script>
的字符或 </script>
.
在 Expresso 中测试并稍微修改了输入(我在各处添加了 <
和 >
以模拟损坏):
关于html - RegEx 仅当字符串出现在特定 HTML 元素内时才匹配字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29558279/
我是一名优秀的程序员,十分优秀!