![](/img/trans.png)
[英]Extracting numbers with regex in ruby from a numbers divided by a dot (thousand delimiter)
[英]extracting numbers from string without the use of regex in ruby
string = "12abc3 def*40"
如何在不使用正則表達式的情況下從該字符串中提取12,3和40? 這是我的方法在正則表達式的幫助下。
def numberExtraction(str)
str_array = str.split(/\D/).delete_if {|char| char == ""}
str_array.map(&:to_i)
end
使用Enumearble#chunk :
def extract_numbers(str)
str.
chars.
chunk { |char| ('0'..'9').include? char }.
select { |is_digit, _| is_digit }.
map { |_, chars| chars.join }
end
extract_numbers("12abc3 def*40")
#=> ["12", "3", "40"]
您可以迭代每個char並檢查char.to_i是否與char相同,如果是這樣映射它。
檢查一下
str = "12abc3 def*40"
str.each_char do |b|
puts b unless b.ord > 57 or b.ord < 48
end
要么
str.chars { |b| puts b unless b.ord > 57 or b.ord < 48 }
兩者都是一樣的
結果
1
2
3
4
0
我建議使用String#scan
:
str = "12abc3 def*40"
str.scan(/\d+/)
#=> ["12", "3", "40"]
str.scan(/\d+/).map(&:to_i)
#=> [12, 3, 40]
它使用正則表達式,但正則表達式正是手頭任務的正確工具。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.