Home > Software engineering >  Perl Regex to Match Colon Occurrence if Present
Perl Regex to Match Colon Occurrence if Present

Time:07-01

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.

CodePudding user response:

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

  • Related