当特定单词不属于链接时,捕获所有出现的特定单词 [英] Capturing all the occurrences of a specific word when is not part of a link

查看:54
本文介绍了当特定单词不属于链接时,捕获所有出现的特定单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PCRE2 方言从 HTML 文本中获取所有出现的单词apple"的正则表达式.但不包括当苹果这个词是链接的一部分.
我是 Regex 的初学者,可能我犯了一个很简单的错误.

I'm trying to get with a regex using PCRE2 dialect from an HTML text all the occurrences of the word 'apple'. But excluding when the word apple it's part of a link.
I'm quite a beginner with Regex, probably I'm doing quite a simple mistake.

\bapple\b

因此,以下文本必须与第一次匹配,但不能与第二次和第三次匹配.

So, the following text has to match the first occurrence but not the second and third one.

Lorem ipsum apple sit amet, consectetur <a href="#">apple</a> elit <a href="/test/apple">lorem</a>. 

我做错了什么?

推荐答案

在 PCRE 中,你可以使用这个正则表达式:

In PCRE, you may use this regex:

~(?is)<a .*?</a>(*SKIP)(*F)|\bapple\b~

正则表达式演示

正则表达式详情:

  • (?is): Enable ignore case and DOTALL modes
  • <a .*?</a>: Match text from <a to </a> to skip all <a> tage
  • (*SKIP)(*F): together provide a nice alternative of restriction that you cannot have a variable length lookbehind in PCRE regex
  • |: OR
  • \bapple\b: Match word apple

这篇关于当特定单词不属于链接时,捕获所有出现的特定单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆