Steph
Steph

Reputation: 27

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

Upvotes: 1

Views: 64

Answers (3)

Guillaume Bihet
Guillaume Bihet

Reputation: 705

If you want to allow your answer to be complex you should rather not go for \w+ but rather /.*\.(.*?)\}/ (basically that would match anything between a . and a }

ex:

> smartcode = '{{question.complex answer w/ more than 1 kind of symbols such as $}}'
> smartcode.match(/\.(\w+)/)[1]
=> "complex"
> smartcode.match(/.*\.(.*?)\}/)[1]
=> "complex answer w/ more than 1 kind of symbols such as $"

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

You can use

smartcode[/{{[^{}]*\.([^{}]*)}}/, 1]

The /{{[^{}]*\.([^{}]*)}}/ regex (see the regex demo) matches

  • {{ - a {{ text
  • [^{}]* - any zero or more chars other than { and } as many as possible
  • \. - a dot
  • ([^{}]*) - Group 1 (this substring will be returned with the [/regex/, num] construct): any zero or more chars other than { and }, as many as possible
  • }} - a }} text.

See the Ruby code online:

smartcode = '{{question.answer}}'
puts smartcode[/{{[^{}]*\.([^{}]*)}}/, 1]
# => answer

If you need to get multiple matches, use .scan:

smartcode = '{{question.answer}} and {{question.author}}'
puts smartcode.scan(/{{[^{}]*\.([^{}]*)}}/)
# => ['answer', 'author']

See this Ruby code demo.

Upvotes: 0

spickermann
spickermann

Reputation: 107142

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"

Upvotes: 2

Related Questions