如何模式匹配字符串中的字符串,然后将其提取到变量中
我遇到了一个我无法解决的问题。我已将网页中的一行提取到变量中。为了论证,可以说这是:
rhyme = "三只盲鼠版本 6.0"
我希望能够首先找到这个字符串 (6.0) 中的版本号,然后将该数字提取到另一个单独的变量中 - (我想要具体提取不超过“6.0”)
我希望我已经足够澄清这一点,如果没有,请询问我您需要知道的任何信息,我会尽快回复您。
I have come across a problem that I cannot see to solve. I have extracted a line from a web page into a variable. lets say for argument sake this is:
rhyme = "three blind mice Version 6.0"
and I want to be able to first of all locate the version number within this string (6.0) and secondly extract this number into another seperate variable - (I want to specifically extract no more than "6.0")
I hope I have clarified this enough, if not please ask me anything you need to know and I will get back to you asap.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您需要决定版本号的模式应该是什么。一种可能是
\d+(\.\d+)*$
(在字符串末尾跟随零个或多个数字(点后跟数字))。然后你可以使用
String#[]
来获取与模式匹配的子字符串:First you need to decide what the pattern for a version number should be. One possibility would be
\d+(\.\d+)*$
(a number followed by zero or more (dot followed by a number) at the end of the string).Then you can use
String#[]
to get the substring that matches the pattern:您需要使用正则表达式。我会使用 rhyme.scan(/(\d+\.\d+)/) 因为如果发生多个匹配它可以返回一个数组。它还可以占用一个块,以便您可以添加范围检查或其他检查以确保捕获正确的块。
如果可以相信输入仅产生一个匹配项,或者如果您始终要使用第一个匹配项,则可以使用此 答案。
编辑:因此,在我们讨论之后,就可以答案。
You need to use regular expressions. I would use
rhyme.scan(/(\d+\.\d+)/)
since it can return an array if multiple matches occur. It can also take a block so that you can add range checks or other checks to ensure the right one is captured.If the input can be trusted to yield only one match or if you always are going to use the first match you can just use the solution in this answer.
Edit: So after our discussion just go with that answer.
正则表达式匹配一个数字,后跟一个句点,然后是另一个数字。括号捕获其内容。由于它是第一对括号,因此它被映射到
$1
。The regexp matches a digit, followed by a period, followed by another digit. The parenthesis captures its contents. Since it is the first pair of parenthesis, it is mapped to
$1
.