【问题标题】:Regex specific exclusions正则表达式特定排除
【发布时间】:2018-01-08 18:04:31
【问题描述】:

我需要一个匹配第一次出现单词的正则表达式模式,不包含在“a”标签内,但可以包含在任何其他标签内标签。

即负前瞻以查看匹配的单词是否在 a' 标记内,如果是,则忽略并继续寻找有效匹配。

示例字符串

有效载荷 1:

<p>Sample 1 <a href="shouldNotMatchWrappedInA">wordToMatch</a> some random text 
to not be matched followed by wordToMatch, this should work.</p>

预期结果1:

wordToMatch ("Not the one inside of a' tags but the following one")

有效载荷 2:

<p>Sample 2 <a href="shouldNotMatchWrappedInA">wordToMatch</a> some random text 
to not be matched followed by <b>wordToMatch</b> this should work.</p>

预期结果 2:

wordToMatch ("The one inside of the b' tags")

有效载荷 3:

<p>Sample 3 <a href="shouldNotMatchWrappedInA">wordToMatch</a> some 
random text to not be matched followed by wordToMatch followed by 
further occurrences of wordToMatch which should not be matched.</p>

预期结果 3:

wordToMatch ("The second occurrence of the term")

请帮忙:'(

使用的语言是 Java

【问题讨论】:

标签: regex regex-lookarounds regex-group


【解决方案1】:

我能想到的简单模式是:

(?:<a.*>)(\w+)(?:<\/a>)

为了测试,请运行 perl 脚本:

$result  = "<p>Sample 1 <a href=\"shouldNotMatchWrappedInA\">wordToMatch</a> some random text to not be matched followed by <b>wordToMatch</b>, this should work.</p>";

$result  =~  m/(?:<a.*>)(\w+)(?:<\/a>).*(\1).*/;

print $2; 

注意你需要使用第二个匹配组。 不幸的是,我不能用 JAVA 给你答案。

【讨论】:

  • 我已经尝试过这种模式,但不幸的是它不会在“a”标签内产生 wordToMatch not 的预期结果。不过感谢您的回复。
  • 我更新了模式,但是搜索下一个相同的单词很奇怪
猜你喜欢
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多