简体   繁体   中英

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".

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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