perl正则以匹配结肠发生的情况如果存在

发布于 2025-02-12 10:56:56 字数 467 浏览 0 评论 0 原文

如果第一个单词包含“蓝色”,则我想将REGEX与字符串中的任何字母/number/下划线匹配以及双结肠匹配。

例如,

Blue Red Yellow //return Red
Blue Red::Orange Yellow //return Red::Orange
Purple Red Yellow //return nothing
Blue R_E_D //return R_E_D 
Red Blue //return nothing 
Blue.ish Yellow //return Yellow

我尝试了/blu \ s+\ s+(\ w+)/,除了 :: 案例外,它都可以使用。在检查 W+之后,我如何添加匹配项,如果存在 W+,也可以匹配双结肠,而不必要求我的等级仅在 :: 也存在的情况下匹配。

I want to regex match any alphabet/number/underscore character as well as double colons in a string if the first word contains "Blue".

For example,

Blue Red Yellow //return Red
Blue Red::Orange Yellow //return Red::Orange
Purple Red Yellow //return nothing
Blue R_E_D //return R_E_D 
Red Blue //return nothing 
Blue.ish Yellow //return Yellow

I tried /Blu\S+\s+(\w+)/ and it's working for all cases except the :: case. How can I add a match after checking for w+ to match double colons as well IF present without having to mandate my regex to only match if there is a :: present as well.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝眼泪 2025-02-19 10:56:56

您可以使用捕获组并重复单词char或:

^Blue\b\S*\h+([\w:]+)

模式匹配:

  • ^或使用 \ b (如果不是在开始
  • 蓝色\ b \ s*匹配单词 blue 和可选的非白色whitspace cahrs
  • \ h+ 匹配1+空格
  • ([\ w:]+)捕获1+字char或:在第1组中

REGEX DEMO

或使用 \ k 清除匹配缓冲区:

^Blue\b\S*\h+\K[\w:]+

regex demo

如果该单词不能以结肠开头,但应该具有 :: 在之间和 bluebird 之间也应如 @ ikegami :

\bBlue\S*\h+\K\w+(?:::\w+)*

You can use a capture group and repeat the word char or :

^Blue\b\S*\h+([\w:]+)

The pattern matches:

  • ^ Or use \b if not at the start
  • Blue\b\S* Match the word Blue and optional non whitspace cahrs
  • \h+ Match 1+ spaces
  • ([\w:]+) Capture 1+ word chars or : in group 1

Regex demo

Or using \K to clear the match buffer:

^Blue\b\S*\h+\K[\w:]+

Regex demo

If the word can not start with a colon but should have :: in between and Bluebird should also match as noted in the comments by @ikegami:

\bBlue\S*\h+\K\w+(?:::\w+)*

Regex demo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文