簡體   English   中英

使用Regex用Ruby在字符串中找到兩個數字

[英]Find two numbers in string with Ruby using Regex

我有一個看起來像這樣的字符串:

結果1-10 / 20

如何在Ruby中使用正則表達式找到該句子的數字10和20?

就像是:

first_number, second_number = compute_regex(my_string)...

謝謝

像這樣:

first, second = *source.scan(/\d+/)[-2,2]

說明

\\d+匹配任何數字

scansource找到其正則表達式參數的所有匹配項

[-2,2]返回數組中的最后兩個數字:從結尾處的索引-2開始,返回下一個2

* splat運算符將這兩個匹配項分解為變量firstsecond注意 :此運算符不是必需的,您可以刪除它,我喜歡這個 概念

嘗試這個:

a = "Results 1 - 10 of 20"
first_number, second_number = a.match(/\w+ (\d) \- (\d+) of (\d+)/)[2..3].map(&:to_i)

map塊是必需的,因為返回的regexp MatchData對象是字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM