简体   繁体   中英

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

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\"\=\>\".\"/)

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

This regex will match your string:

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

you can try rubular.com for testing

It looks like you're trying to truncate a sentence. You can split the sentence either on punctuation, or even on words.

mystring.split(".")
mystring.split("word")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM