Search code examples
ruby-on-railsregexrubysplitcurly-braces

Refactoring 2 Regexps


I want to split the string

smartcode = '{{question.answer}}'

to obtain just eventually

'answer'

I know this works

smartcode.split(/\{{(.*?)\}}/).last.split(/\.(?=[\w])/).last

but it's not the better way i guess...


Solution

  • I suggest:

    smartcode = '{{question.answer}}'
    smartcode.match(/\.(\w+)/)[1]
    #=> "answer"
    

    Or when you want to ensure that the specific structure with the surrounding brackets and two words separated by a dot:

    smartcode.match(/{{\w+\.(\w+)}}/)[1]
    #=> "answer"