如何模式匹配字符串中的字符串,然后将其提取到变量中

发布于 2024-09-24 14:22:24 字数 206 浏览 3 评论 0原文

我遇到了一个我无法解决的问题。我已将网页中的一行提取到变量中。为了论证,可以说这是:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

画中仙 2024-10-01 14:22:24

首先,您需要决定版本号的模式应该是什么。一种可能是 \d+(\.\d+)*$ (在字符串末尾跟随零个或多个数字(点后跟数字))。

然后你可以使用 String#[] 来获取与模式匹配的子字符串:

rhyme[ /\d+(\.\d+)*$/ ] #=> "6.0"

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[ /\d+(\.\d+)*$/ ] #=> "6.0"
爱的故事 2024-10-01 14:22:24

您需要使用正则表达式。我会使用 rhyme.scan(/(\d+\.\d+)/) 因为如果发生多个匹配它可以返回一个数组。它还可以占用一个块,以便您可以添加范围检查或其他检查以确保捕获正确的块。

version = "0.0"
rhyme = "three blind mice Version 6.0"
rhyme.scan(/(\d+\.\d+)/){|x| version = x[0] if x[0].to_f < 99}
p version

如果可以相信输入仅产生一个匹配项,或者如果您始终要使用第一个匹配项,则可以使用此 答案

编辑:因此,在我们讨论之后,就可以答案

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.

version = "0.0"
rhyme = "three blind mice Version 6.0"
rhyme.scan(/(\d+\.\d+)/){|x| version = x[0] if x[0].to_f < 99}
p version

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.

生生漫 2024-10-01 14:22:24
if rhyme =~ /(\d\.\d)/
    version = $1
end

正则表达式匹配一个数字,后跟一个句点,然后是另一个数字。括号捕获其内容。由于它是第一对括号,因此它被映射到$1

if rhyme =~ /(\d\.\d)/
    version = $1
end

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文