开发者

What is the best way to get 51, out of the following string

开发者 https://www.devze.com 2023-04-08 05:23 出处:网络
What is the best way to get \'51\', out of the following string in ruby : \"<https://api.example.com/users/lgs/api?page=2>; rel=\\\"next\\\", <https://api.example.com/users/lgs/api?page=51&g

What is the best way to get '51', out of the following string in ruby :

"<https://api.example.com/users/lgs/api?page=2>; rel=\"next\", <https://api.example.com/users/lgs/api?page=51>; rel=\"last\""

Thanks in advanc开发者_高级运维e Luca


If you know there're only two numbers in that string then this is enough:

str = '"<https://api.example.com/users/lgs/api?page=2>; rel=\"next\", <https://api.example.com/users/lgs/api?page=51>; rel=\"last\""'
p str.scan(/\d+/).last #=> "51"

If not then provide more detail to make the regex more precise. Also you can add to_i if you need the answer as a number.


You can use regexp in this way:

res = str.match /.page=(\d+)./

in this way you are "capturing all the digits between "(" and ")" (in the last token), and you result will be store in

res.captures.first (or simply in $1 variable)

0

精彩评论

暂无评论...
验证码 换一张
取 消