[英]What's the “ruby way” to parse a string for a single key/value?
我正在尝试解析一个多行字符串,并按照模式获取该行的其余部分。
文本:
hello john your username is: jj thanks for signing up
我想提取jj,即“你的用户名是:”之后的所有内容
单程:
text = "hello john\nyour username is: jj\nthanks for signing up\n"
match = text[/your username is: (.*)/]
value = $1
但这让我想起了perl ......并且不像我告诉ruby那样自然地“阅读”。
有更干净的方式吗? AKA“红宝石”的方式?
谢谢
您的代码几乎是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"
#=> #<MatchData:0x557f94>
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.