什么是“红宝石方式"?解析单个键/值的字符串? [英] What's the "ruby way" to parse a string for a single key/value?
本文介绍了什么是“红宝石方式"?解析单个键/值的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试解析多行字符串并按照模式获取行的其余部分.
文字:
<前>你好约翰你的用户名是:jj感谢您的注册我想提取 jj,也就是您的用户名是:"之后的所有内容
一种方式:
text = "hello john\n你的用户名是:jj\n感谢注册\n"match = text[/您的用户名是:(.*)/]价值 = 1 美元
但这让我想起了 perl ......并且不像我被告知 ruby 应该那样自然地阅读".
有更干净的方法吗?又名红宝石"方式?
谢谢
解决方案
您的代码几乎是 Ruby 的方式.如果不想使用全局的 $1
,可以使用 2 arg 版本 String#[]
:
match = text[/你的用户名是:(.*)/, 1]
I am trying to parse a multi line string and get the rest of the line following a pattern.
text:
hello john your username is: jj thanks for signing up
I want to extract jj, aka everything after "your username is: "
One way:
text = "hello john\nyour username is: jj\nthanks for signing up\n"
match = text[/your username is: (.*)/]
value = $1
But this reminds me of perl... and doesn't "read" as naturally as I am told ruby should.
Is there a cleaner way? AKA A "ruby" way?
Thanks
解决方案
Your code is pretty much the Ruby way. If you don't want to use the global $1
, you can use the 2 arg version String#[]
:
match = text[/your username is: (.*)/, 1]
这篇关于什么是“红宝石方式"?解析单个键/值的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文