davideghz davideghz - 1 year ago 74
Ruby Question

ruby regex extract word between single quotes

I'm looking for a regex to match:

ciao: c'iao 'ciao'


ciao #every word excluding non-word character
c'iao #including apostrophes
ciao #excluding the quotes ''

So far I've been able to match the first 2 requirements with:


but I'm struggling with extracting word between single quotes (w/o including the quotes). Note that I won't have a case where a word with apostrophe is included between quotes (like 'c'iao')

I've seen many similar Q&A but couldn't find any suiting my needs; Extra points for an answer that includes a brief explanation :)

Answer Source

You can use the following expression:


See the Rubular demo

The expression matches:

  • \w+ - 1 or more word chars
  • (?:'\w+)* - zero or more sequences (as (?:...)* is a non-capturing group that groups a sequence of subpatterns quantified with * quantifier matching 0 or more occurrences) of:
    • ' - apostrophe
    • \w+ - 1 or more word chars.

See a short Ruby demo here:

"ciao: c'iao 'ciao'".scan(/\w+(?:'\w+)*/)
# => [ciao, c'iao, ciao]