[英]How to remove all non-digits from a string in ruby?
用戶以下列形式輸入數字:
1-800-432-4567
800-432-4567
800.432.4566
(800)432.4567
+1(800)-432-4567
800 432 4567
我希望所有這些都變成一個剝離版本,沒有像18004324567
這樣的特殊字符。 數據以String
的形式出現,因此不需要進行字符串檢查。
我的方法如下:
def canonical_form number
a = remove_whitespaces number #to clear all whitespaces in between
a.gsub(/[()-+.]/,'')
end
def remove_whitespaces number
number.gsub(/\s+/,'') #removes all whitespaces
end
有一個更好的方法嗎? 可以使用canonical_form
方法中的canonical_form
則表達式檢查空格,而無需額外的空格方法嗎? 如何以更簡潔的方式對其進行重構或完成?
如果String的tr
方法的第一個參數以^
開頭,那么它表示除列出的所有字符之外的所有字符。
def canonical_form str
str.tr('^0-9', '')
end
上面的幾個解決方案 - 我對一些人感興趣的基准測試:
str = "1-800-432-4567"
Benchmark.ms { 10000.times{str.scan(/\d/).join} }
#=> 69.4419999490492
Benchmark.ms { 10000.times{str.delete('^0-9')} }
#=> 7.574999995995313
Benchmark.ms { 10000.times{str.tr('^0-9', '')} }
#=> 7.642999989911914
Benchmark.ms { 10000.times{str.gsub(/\D+/, '')} }
#=> 28.084999998100102
您可以查找所有數字,而不是刪除特殊字符。 就像是:
str = "1-800-432-4567"
str.scan(/\d/).join
#=> "18004324567"
str = "(800)432.4567"
str.scan(/\d/).join
#=> "8004324567"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.