簡體   English   中英

帶正則表達式的數組映射

[英]Array map with regular expression

我有如下數組:

arr = [
  nil,
  6,
  "17 to 23 ||'.'||24 to 25 (add a decimal at 10th place)",
  nil,
  nil,
  "37 to 51 ||'.'||52 to 53 (add a decimal at 100th place)",
  nil
]

我想將此數組轉換為以下內容:

arr = [
  nil,
  6,
  "10th",
  nil,
  nil,
  "100th",
  nil
]

即從字符串"17 to 23 ||'.'||24 to 25 (add a decimal at 10th place)" ,我需要括號中提到的數字。

我嘗試了以下代碼,但無法正常工作:

arr.map! {|e| e[/^.*?add.*?(\d+)th.*?$/]}

您的代碼失敗,因為obj[pattern]僅適用於字符串,不適用於nil或整數(有Integer#[]但它還有其他功能):

nil[/foo/] #=> NoMethodError: undefined method `[]' for nil:NilClass
123[/foo/] #=> TypeError: no implicit conversion of Regexp into Integer

您可以使用=~代替,它在Object上定義並被子類覆蓋,例如String

arr.map {|e| e =~ /(\d+th)/ ? $1 : e }
#=> [nil, 6, "10th", nil, nil, "100th", nil]

如果e匹配/(\\d+th)/ ,則返回$1 (第一個捕獲組),否則返回e本身。

您還可以使用更具體的模式:

/add a decimal at (\d+th) place/

暫無
暫無

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

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