簡體   English   中英

使用R中的正則表達式從文件名中提取模式?

[英]Extract pattern from filename using regex in R?

我有以下字符串:

“UNKNOWN _ {_的requestId ___ b9b6bcc4-c163-45d7-82d9-423a96cf5fe1 _,_設備ID ___ 9c84f871-9e95-45d5-9335-12e7d42b96a0 _} _ 2018-08-15-15-43-01-296_529307b7-6316-4cdc-ab53-2e1158c651c6.txt”

我想提取529307b7-6316-4cdc-ab53-2e1158c651c6部分(_和.txt之間的最后一部分)。

這是我正在嘗試使用正則表達式做的事情:

^\\_\\w\\.txt但沒有運氣,我一直在玩這個,請告知策略是什么以及如何“攻擊”這個。

你可以用

sub("^.*_(.*)\\.txt$", "\\1", x)

請參閱正則表達式演示

sub將執行單個seasrch和替換操作。 如果字符串符合以下條件,它將找到匹配項:

  • ^字符串的開始
  • .*_ -任何0+字符,盡可能多,直到最后_
  • (.*) -任何0+字符(捕獲到組1,以后稱為與\\1從替換模式),盡可能多的,至多並包括...
  • \\\\.txt$ - .txt.必須逃到匹配一個點)在字符串(結束$ )。

R演示

x <- "UNKNOWN_{_requestID___b9b6bcc4-c163-45d7-82d9-423a96cf5fe1_,_deviceID___9c84f871-9e95-45d5-9335-12e7d42b96a0_}_2018-08-15-15-43-01-296_529307b7-6316-4cdc-ab53-2e1158c651c6.txt"
sub("^.*_(.*)\\.txt$", "\\1", x)
## => [1] "529307b7-6316-4cdc-ab53-2e1158c651c6"

這是使用工具中隱藏的寶石。

x <- "UNKNOWN_{_requestID___b9b6bcc4-c163-45d7-82d9-423a96cf5fe1_,_deviceID___9c84f871-9e95-45d5-9335-12e7d42b96a0_}_2018-08-15-15-43-01-296_529307b7-6316-4cdc-ab53-2e1158c651c6.txt"

out <- strsplit(x, "_")[[1]]
out <- out[length(out)]
tools::file_path_sans_ext(out)

[1] "529307b7-6316-4cdc-ab53-2e1158c651c6"

你可以嘗試一下嗎?

gsub(".*_|\\.txt","",x)

輸出如下。

[1] "529307b7-\n6316-4cdc-ab53-2e1158c651c6"

說明:僅出於解釋目的添加以下內容。

gsub(     ##Using gsub(Global substitution function of R to perform multiple substitution on variables)
".*_      ##Mentioning REGEX to select everything from starting till _(underscore)
|         ##|(pipe) defines OR so it should match either previous or coing REGEX in varibale's value.
\\.txt"   ##\\. means escaping DOT so that DOT should be treated as a DOT not with its special meaning so it should match string .txt
,""       ##If above mentioned REGEXs any one of them OR both matches then substitute them with "" means NULL.
,x)       ##Mentioning variable named x on which we have to perform gsub.

其中輸入變量x的值如下。

x <- "UNKNOWN_{_requestID___b9b6bcc4-c163-45d7-82d9-423a96cf5fe1_,_deviceID
___9c84f871-9e95-45d5-9335-12e7d42b96a0_}_2018-08-15-15-43-01-296_529307b7-
6316-4cdc-ab53-2e1158c651c6.txt"

申請2次分:

    text <- c("UNKNOWN_{_requestID___b9b6bcc4-c163-45d7-82d9-423a96cf5fe1_,_deviceID___9c84f871-9e95-45d5-9335-12e7d42b96a0_}_2018-08-15-15-43-01-296_529307b7-6316-4cdc-ab53-2e1158c651c6.txt" )
    sub("\\.txt.*", "", sub(".*\\_", "", text)) 

暫無
暫無

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

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