简体   繁体   English

用Ruby中的正则表达式提取字符串中的数字

[英]extract number in string with regex in ruby

I have this string 我有这串

url = "#AppDashboardPlace:p=io.transporterapp.deep.test1&appid=4975603106871514996"

I would like to get 4975603106871514996 我想得到4975603106871514996

I have tried that 我试过了

url.to_s[/\appid\=(.*?)\&/, 1]
=> nil

Your regex doesn't match because there's no & after the appid value. 您的正则表达式不匹配,因为appid值后没有& Try this: 尝试这个:

url.to_s[/appid=(\d+)/,1]

If you left the matching part as .*? 如果将匹配的部分留为.*? with nothing after it, it would match the minimum amount of the string possible, which is the empty string. 后面没有任何内容,它将匹配可能的最小字符串量,即空字符串。 If you know that the appid is the very end of the string, then you could use .* without the ? 如果您知道appid是字符串的结尾,那么可以使用.*而不使用? , but it's best to be precise and specify that what you're looking for is a series of one or more ( + ) decimal digits ( \\d ). ,但最好精确一点,并指定要查找的是一系列一个或多个( + )十进制数字( \\d )。

You could use String#match with the \\d regex matcher, for matching on \\d+ , which means one or more digit. 您可以将String#match与\\ d正则表达式匹配器一起使用,以在\\d+上进行匹配,这意味着一个或多个数字。

url = "#AppDashboardPlace:p=io.transporterapp.deep.test1&appid=4975603106871514996"
match = url.match(/appid\=(\d+)/)
# => #<MatchData "appid=4975603106871514996" 1:"4975603106871514996">
puts match[0]
# => "appid=4975603106871514996"
puts match[1]
# => "4975603106871514996"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM