[問題] 用regex從檔名中拿出數字部分
[問題敘述]:
請教各位先進,
我要從圖案檔名中拿數字以及括號中的數字部分。我的檔名有兩個規律性,目前我已經
可以各寫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,
3年前
, 1F
08/06 12:53, 1F
→
08/06 12:53,
3年前
, 2F
08/06 12:53, 2F
→
08/06 12:54,
3年前
, 3F
08/06 12:54, 3F
→
08/06 12:58,
3年前
, 4F
08/06 12:58, 4F
→
08/06 13:00,
3年前
, 5F
08/06 13:00, 5F
→
08/06 13:01,
3年前
, 6F
08/06 13:01, 6F
→
08/06 13:03,
3年前
, 7F
08/06 13:03, 7F
→
08/11 10:09, , 8F
08/11 10:09, 8F
R_Language 近期熱門文章
PTT數位生活區 即時熱門文章