正则表达式:仅当字符串不是标签的一部分时才匹配字符串

发布于 2024-08-03 04:20:26 字数 228 浏览 6 评论 0原文

我只尝试匹配不属于 html 标签一部分的字符串。

例如,搜索字符串时:“abc”。 abc def 应该匹配 <代码>

foo bar foo abc foo bar

应该匹配

,但是 foo 不应匹配。

感谢您的帮助!

I am trying to match a string only if it is not part of an html tag.

For example when searching for the string: "abc".
<a href="foo.html">abc def</a> should match
<p> foo bar foo abc foo bar</p> should match

but
<a href="abc.html">foo</a> should not match.

Thanks for the help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

喜爱皱眉﹌ 2024-08-10 04:20:26

我真的不会使用正则表达式来匹配 HTML,因为 HTML 不是常规的,而且有大量的边缘情况会让你陷入困境。对于除最简单情况之外的所有情况,我都会使用 HTML 解析器(例如 这个 对于 PHP)。

I really wouldn't use regexps to match HTML, since HTML isn't regular and there are a load of edge cases to trip you up. For all but the simplest cases I'd use an HTML parser (e.g. this one for PHP).

美男兮 2024-08-10 04:20:26

Brian 说得有道理,无论如何,如果你想使用正则表达式,那么它适合你的输入:

.*>[^<]*abc[^<]*<.*

Brian has got a point, anyway, if you wish to use a regex, that one suits you inputs:

.*>[^<]*abc[^<]*<.*
断舍离 2024-08-10 04:20:26

我非常确信任何正则表达式都会在某些 CDATA 部分上崩溃。

I'm quite convinced that any regex is going to break on some CDATA sections.

日久见人心 2024-08-10 04:20:26

您正在寻找的是 DOM 解析器。这将删除所有 HTML 并为您提供正在检查的页面的纯文本,然后您可以对其进行匹配。不确定你的用例是什么,但我不假设你没有操作 DOM,否则你会使用 JavaScript。

如果您只是提取信息,请使用 简单 HTML DOM 解析器 解析页面,然后匹配对比你可以从解析的对象中获得的纯文本。

What you're looking for is a DOM parser. That will strip out all the HTML and provide you the plain text of the page you're examining, which you can then match on. Not sure what your use case is, but I'm not assuming you're not manipulating the DOM, or else you'd be using JavaScript.

If you're just extracting information, parse the page using something like The Simple HTML DOM Parser, and then match against the plain text you can get from the parsed object.

小镇女孩 2024-08-10 04:20:26

虽然我也同意 Brian评论,我经常用正则表达式进行快速而肮脏的解析,对于你的情况,我' d 使用这样的东西:

  • “序列化”数据

<前><代码>s/[\r\n]//
s///
s//>\n/

  • 然后简单地过滤所有以 < 开头的行
s/^<.*//

剩下的只是文本(可能还有很多空白)。尽管这不是关于正则表达式,而是更多关于搜索和替换。

While I too agree with Brian's comment, i often do quick and dirty parsing with regular expressions, and for your case, i'd use something like this:

  • "serialize" the data
s/[\r\n]//
s/<!\[CDATA\[.*?]]>//
s/</\n</
s/>/>\n/
  • then simply filter all lines that begin with <
s/^<.*//

What you're left with is just the text (and possibly a lot of white-space). Though this is less about regular expressions and more about search and replace.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文