[問題] 用regex從檔名中拿出數字部分

看板R_Language作者 (luen)時間2年前 (2021/08/06 11:53), 編輯推噓1(106)
留言7則, 2人參與, 2年前最新討論串1/1
[問題敘述]: 請教各位先進, 我要從圖案檔名中拿數字以及括號中的數字部分。我的檔名有兩個規律性,目前我已經 可以各寫1個pattern拿出我要的部分,希望有先進指點如何只用一個pattern就可以從這 2類檔名中拿出數字及括號中數字部分。 number1_[number2,number3] 3個number的位數不是固定的。 [程式範例]: 我想從以下兩類檔名中拿出 "200330_[50706,13606]" 第1類檔名例子: 檔名在pattern之前有字串,字串裡可能有數字,字母或special characters x2 <- "B16F10 KO 200330_[50706,13606]_CD8_path_view.jpg" gsub(pattern = ".*( )(\\d+_\\[\\d+,\\d+\\]).*" ,replacement= "\\2" # get pattern within the 2nd pair of brackets ,x=x2) # [1] "200330_[50706,13606]" 第2類檔名例子: 檔名以pattern開號 x3 <- "200330_[50706,13606]_CD8_path_view.jpg" gsub(pattern = "(\\d+_\\[\\d+,\\d+\\]).*" ,replacement= "\\1" # get pattern within the 1st pair of brackets ,x=x3) # [1] "200330_[50706,13606]" 請教如何用1個pattern就能從x2, x3拿出200330_[50706,13606]? 很明顯地,.* 不能描述沒有東西。但我不知道為何以下的gsub只拿出1位數字 0_[50706,13606]? gsub(pattern = ".*(\\d+_\\[\\d+,\\d+\\]).*" ,replacement= "\\1" # get pattern within the 1st pair of brackets ,x=x3) # [1] "0_[50706,13606]" 我把以上程式放在 hackMD裡 https://hackmd.io/@Chang/string-manipulation-in-R 請看第一部分 Examples of subsetting numbers from image file names 謝謝指點 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.122.149.154 (澳大利亞) ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1628222030.A.D3E.html

08/06 12:53, 2年前 , 1F
str_sub(字串,str_locate(字串,"\\d{6}..\\d{5}.\\d{5}
08/06 12:53, 1F

08/06 12:53, 2年前 , 2F
.))
08/06 12:53, 2F

08/06 12:54, 2年前 , 3F
package stringr
08/06 12:54, 3F

08/06 12:58, 2年前 , 4F
數字的位數不是固定的
08/06 12:58, 4F

08/06 13:00, 2年前 , 5F
在我的例子裡是6及5位數。數據裡可能是1到7位數
08/06 13:00, 5F

08/06 13:01, 2年前 , 6F
那就把{6}改成{1,7}看看?
08/06 13:01, 6F

08/06 13:03, 2年前 , 7F
是不是把//d{6} 及 //d{5}改成//d{+}就可以了?
08/06 13:03, 7F
文章代碼(AID): #1X3B9Eq- (R_Language)
文章代碼(AID): #1X3B9Eq- (R_Language)