解析单个键/值的字符串的“ruby方式”是什么?

我正在尝试解析多行字符串并获取模式后面的其余行。

文本:

你好约翰
您的用户名是:jj
感谢您的注册

我想提取jj,即“你的用户名是:”之后的所有内容

单程:

text = "hello john\nyour username is: jj\nthanks for signing up\n" match = text[/your username is: (.*)/] value = $1 

但这让我想起了perl ……并且不像我告诉ruby那样自然地“阅读”。

有更干净的方式吗? AKA一种“ruby”的方式?

谢谢

您的代码几乎是Ruby方式。 如果您不想使用全局$1 ,则可以使用2 arg版本String#[]

 match = text[/your username is: (.*)/, 1] 

split命令非常有用。 它将一个字符串分成一个子串数组,分隔你传入的任何内容。如果你没有给它任何参数,它就会在空格上分割。 所以,如果你知道你要找的单词是第五个“单词”(在空格和返回字符上分开),你可以这样做:

text =“你好john \ nyour用户名是:jj \ nthanks用于注册\ n”
匹配= text.split [5]

..但也许这不是足够的自我记录,或者你想允许多字匹配。 你可以这样做:

中线= text.split( “\ n” 个)[1]
match = midline.split(“username is:”).last

或者这可能是更简洁的方式:

match = text [/ username is:(。*)/,1]

不确定它是否是Ruby’ish,但另一种选择:

 >> text = "hello john\nyour username is: jj\nthanks for signing up\n" >> text.match(/your username is: (.*)/)[1] => "jj" 

还有Regexp#match ,它返回一个MatchData对象,它包含你可能想要的所有信息。

 irb> match = /your username is: (.*)/.match "hello john\nyour username is: jj\nthanks for signing up\n" #=> # irb> match.pre_match #=> "hello john\n" irb> match.post_match #=> "\nthanks for signing up\n" irb> match[0] #=> "your username is: jj" irb> match[1] #=> "jj"