【发布时间】:2016-01-09 13:24:07
【问题描述】:
如果它在 html 标签中,我需要编写不匹配单词的正则表达式。
这里是文本示例:
asdd qwe <a href="http://example.com" title="Some title with word qwe" class="external-link" rel="nofollow"> qwe
我的正则表达式现在看起来像这样:
(?!(\<.+))[^a-zA-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ](<class="bad-word"(?: style="[^"]+")?>)?(qwe)(<>)?[^a-zA-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ](?!.+\>)
这有点复杂,但每个人都认为当我在 regex101.com 和 regexr.com 上测试它时,它只匹配 html 标记之后的单词。
知道为什么吗?
编辑:
我不想使用 html 解析器或 DOM 操作,我不想更改这么多代码。
def test_tagged_word_present(self):
input = 'words <a href="example.com" title="title with word qwe" class="external-link" rel="nofollow"> qwe some other words'
expected = 'words <a href="example.com" title="title with word qwe" class="external-link" rel="nofollow"><strong class="bad-word" style="color:red">qwe</strong> some other words'
parser = self.get_test_parser(input, search_word='qwe')
text = parser.mark_words()
self.assertEqual(text, expected)
一切正常,除了正则表达式仍然在标题中缓存qwe。
【问题讨论】:
-
如何使用解析器,将 html 的文本内容反馈给您,然后与文本内容进行匹配?这样一来,标签内的任何文本都不会返回给您。
-
您是否要匹配 标签之外的所有内容?
-
@Ephreal 我正在尝试匹配不在任何类型的 html 标记中的给定单词的每个出现。
-
另一种选择,使用 html 解析器 stackoverflow.com/a/2613246/3526330
-
我认为我无法回答你的问题,确实它并没有按照你在正则表达式 101 中所说的那样做。但是,如果它有效,为什么不使用它呢?您在寻找更简单的示例吗?