【问题标题】:Regex - Match substring outside of hashtags(#)正则表达式 - 匹配主题标签之外的子字符串(#)
【发布时间】:2020-02-09 10:10:07
【问题描述】:

以这个字符串为例:

focus;focus#focus#focus 焦点

如果我想查找子字符串focus,我需要这个结果(粗体匹配):

focus;focus#focus#focus focus

据我所知:(?<!#)(focus)(?!#),演示here
这种模式显然不起作用,因为排除了 # 旁边的子字符串,我也需要包含这些子字符串。

从编程上讲,这就是我需要的:

if !(prefix == "#" && suffix == "#") {
    // Is a match
}

【问题讨论】:

  • 在lookbehind中放一个lookahead:(?<!#(?=focus#))或使用众所周知的回溯控制动词:#focus#(*SKIP)(*F)|focus
  • 避免在正则表达式问题中使用与语言无关的标签(即使使用 pcre 或其他引擎标签),因为实现之间支持的功能可能不同。

标签: regex language-agnostic pcre


【解决方案1】:

您可以使用替代:

(?<!#)focus|focus(?!#)

Updated RegEx Demo

如果前面没有# 或后面没有#,则表示匹配focus。只有在两边都有 # 时才会跳过 focus

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-24
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 2011-11-08
    • 2022-07-11
    相关资源
    最近更新 更多