Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

ruby

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\"\=\>\".\"/)
like image 374
urbanaut Avatar asked Feb 20 '23 09:02

urbanaut


2 Answers

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
like image 109
Chowlett Avatar answered May 18 '23 16:05

Chowlett


your_text = '"content"=>"The text I want to save to a variable"'
/"content"=>"(?<hooray>.*)"/ =~ your_text

Afterwards, hooray local variable will be magically set to contain your text. Can be used to set multiple variables.

like image 34
Boris Stitnicky Avatar answered May 18 '23 17:05

Boris Stitnicky