在字符串上使用Ruby,如何使用RegEx在字符串的两个部分之间进行切片?

时间:2022-07-03 21:37:47

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:

我想我必须使用扫描或切片,但不完全确定如何在不占用文本之前和之后的RegEx标识符的情况下仅提取文本。我试过这个,但它不起作用:

var = mystring.slice(/\"content\"\=\>\".\"/)

4 个解决方案

#1


4  

This should do the job

这应该做的工作

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

Note that:

  • .slice aliases []
  • .slice别名[]

  • 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
  • .slice / []接受第二个参数来选择匹配的组

#2


3  

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.

之后,万岁的局部变量将被神奇地设置为包含您的文本。可用于设置多个变量。

#3


1  

This regex will match your string:

这个正则表达式将匹配您的字符串:

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

you can try rubular.com for testing

你可以尝试rubular.com进行测试

#4


1  

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")

#1


4  

This should do the job

这应该做的工作

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

Note that:

  • .slice aliases []
  • .slice别名[]

  • 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
  • .slice / []接受第二个参数来选择匹配的组

#2


3  

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.

之后,万岁的局部变量将被神奇地设置为包含您的文本。可用于设置多个变量。

#3


1  

This regex will match your string:

这个正则表达式将匹配您的字符串:

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

you can try rubular.com for testing

你可以尝试rubular.com进行测试

#4


1  

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")