首页 > 解决方案 > 排除“|” 从正则表达式

问题描述

我试图排除“|” 来自 youtube 标签列表。

在此处输入图像描述

到目前为止,我能够正则表达式选择所有可爱的标签,例如在下面的字符串中

cute|"cute nail art"|"cute"|"cute"|"fcute"

我能突出“可爱”和可爱| 确切地。问题是“|”。我该如何摆脱它?

我的正则表达式查询是这个("\bcute\b")|(\bcute\b[^\s])

我的预期结果是突出可爱和“可爱”。

任何提示将不胜感激,并感谢您阅读。

标签: regex

解决方案


假设输入是一个标签字符串,|其中一些标签用引号括起来,并且您想以某种方式识别和标记某个标签,无论是原样还是引用,您需要的正则表达式可能如下所示:

(?<=\||^)(cute|"cute")(?=\||$)

在这里检查它:https ://regex101.com/r/acjM8R/3

正则表达式解释

(?<=        # start a positive lookbehind assertion
  ^         # match the beginning of the string
  |         # OR
  \|        # match the character '|' literally (it has a special meaning when not escaped)
)           # end of the lookbehind assertion
(           # start a capturing group; it is also used to group the alternatives
  cute      # match the word 'cute' (the tag) as is
  |         # OR
  "cute"    # match the word "cute" (the tag) when it is quoted
)           # end of the group
(?=         # start a positive lookahead assertion
  \|        # match the character '|' literally (it has a special meaning when not escaped)
  |         # OR
  $         # match the end of the string
)           # end of the lookahead assertion

片段^|\|匹配字符串 ( ^) 的开头或字符|(分隔符)。类似地,片段\||$匹配一个|(分隔符)或字符串的结尾。

肯定断言是对当前匹配点之前 ( (?<= ... )) 或之后 ( (?= ... )) 的字符的测试,该匹配点实际上不消耗任何字符。

总而言之,上面的正则表达式匹配cute或匹配,"cute"但仅当它被分隔符|或字符串边界包围时。

更新

另一种写法(cute|"cute")(("?)cute\2).

该片段("?)捕获一个可选的 ( ?) 引号 ( ")。它后面是实际的标签。该片段的\2意思是“与第二个捕获组相同”,在这种情况下,它是匹配的文本("?)

这意味着如果("?)匹配某物(引用),\2也必须匹配引用。如果匹配一个空字符串(和("?)之间没有引号),也匹配一个空字符串。|cute\2

看到它在这里工作:https ://regex101.com/r/acjM8R/4/


推荐阅读