How to use Ruby for a string, how can I cut between two parts of a string using RegEx?

I just want to save the text between two specific points in a line into a variable. The text will look like this:

..."content"=>"The text I want to save to a variable"}]... 

I assume that I will have to use scan or slice, but not quite exactly how to pull only text without capturing RegEx identifiers before and after the text. I tried this, but this did not work:

 var = mystring.slice(/\"content\"\=\>\".\"/) 
+4
source share
4 answers

This should do the job.

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

Note that:

  • .slice aliases []
  • None of the characters you escaped are special regular expression characters in which you use them.
  • you can β€œgroup” the bit you want to save with ()
  • .slice / [] take the second parameter to select a consistent group
+4
source
 your_text = '"content"=>"The text I want to save to a variable"' /"content"=>"(?<hooray>.*)"/ =~ your_text 

Subsequently, the local variable hooray will be magically configured to contain your text. It can be used to set several variables.

+3
source

This regex will match your string:

 /\"content\"=>\"(.*)\"/ 

you can try rubular.com for testing

+1
source

It looks like you are trying to truncate a sentence. You can divide a sentence either into punctuation, or even into words.

 mystring.split(".") mystring.split("word") 
+1
source

Source: https://habr.com/ru/post/1413802/


All Articles