English 中文(简体)
使用 Ruby 在字符串上, 我如何用 RegEx 切分字符串中两个部分?
原标题:Using Ruby on a string, how can I slice between two parts of the string using RegEx?
  • 时间:2012-05-22 16:15:47
  •  标签:
  • ruby
  • regex

我只想将文本在字符串中两个特定点之间保存到变量中。该文本将看起来是这样的:

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

我想我不得不用扫描或切片,但不确定如何在删除文本之前和之后不抓取RegEx的识别资料。

var = mystring.slice(/"content"=>"."/)
最佳回答

这应该可以做这个工作

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

注意:

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

之后,万雷本地变量将被神奇地设置为包含您的文本。可以用来设置多个变量。

此正则将匹配您的字符串 :

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

您可以尝试 ropular. com 测试

看起来你正试图缩短一个句子。 您可以在标点上, 甚至是单词上, 将句子分割开来 。

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




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签