Using Ruby on a string, how can I slice between two parts of the string using RegEx?

regex, ruby

Solution

This should do the job

var = mystring[/"content"=>"(.*)"/, 1]

Note that:

- `.slice` aliases `[]`

- none of the characters you escaped are special regexp characters where you're using them

- you can "group" the bit you want to keep with `()`

- `.slice` / `[]` take a second parameter to pick a matched group

Problem

I just want to save the text between two specific points in a string into a variable. The text would look like this: ``` ..."content"=>"The text I want to save to a variable"}]... ``` I suppose I would have to use scan or slice, but not exactly sure how to pull out just the text without grabbing the RegEx identifiers before and after the text. I tried this, but it didn't work: ``` var = mystring.slice(/\"content\"\=\>\".\"/) ```

Original source

Related problems