简体   繁体   English

Perl 正则表达式匹配出现的冒号(如果存在)

[英]Perl Regex to Match Colon Occurrence if Present

I want to regex match any alphabet/number/underscore character as well as double colons in a string if the first word contains "Blue".如果第一个单词包含“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.我试过/Blu\S+\s+(\w+)/它适用于除::案例之外的所有案例。 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.如何在检查w+以匹配双冒号以及如果存在时添加匹配项,而不必强制我的正则表达式仅在存在::时才匹配。

You can use a capture group and repeat the word char or :您可以使用捕获组并重复单词 char 或:

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

The pattern matches:模式匹配:

  • ^ Or use \b if not at the start ^或者如果不是在开头使用\b
  • Blue\b\S* Match the word Blue and optional non whitspace cahrs Blue\b\S*匹配单词Blue和可选的非 whitspace cahrs
  • \h+ Match 1+ spaces \h+匹配 1+ 个空格
  • ([\w:]+) Capture 1+ word chars or : in group 1 ([\w:]+)在第 1 组中捕获 1+ 个单词字符或:

Regex demo正则表达式演示

Or using \K to clear the match buffer:或使用\K清除匹配缓冲区:

^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 :如果单词不能以冒号开头,但应在其间有::并且Bluebird也应匹配,如@ikegami的评论中所述:

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

Regex demo正则表达式演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM