Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby capture words between two colons

Tags:

regex

ruby

I want to capture any word between two colons. I tried with this (try on Rubular):

(\:.*\:)

Hello :name:

What are you doing today, :title:?

$:name:, have a lovely :event:.

It works except the last line it captures this:

Match 3
1. :name:, have a lovely :event:

It's getting tripped up by the second (closing) colon and the third (opening) colon. It should capture :name: and :event: individually on that last line.

like image 238
Jumbalaya Wanton Avatar asked Aug 14 '26 11:08

Jumbalaya Wanton


2 Answers

You need a non-greedy regular expression:

(\:.*?\:)

The .*? will match the shortest possible string, whereas .* matches the longest string found.

like image 85
Baldrick Avatar answered Aug 16 '26 23:08

Baldrick


For any word between two colons:

(?<=:)\b.*?\b(?=:)

Rubular link

like image 22
tenub Avatar answered Aug 17 '26 00:08

tenub