简体   繁体   中英

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

I have tried that

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

Your regex doesn't match because there's no & after the appid value. 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 ? , 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 ).

You could use String#match with the \\d regex matcher, for matching on \\d+ , which means one or more digit.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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