在 R 中使用正则表达式提取子字符串

Extract substring using regular expression in R

我是正则表达式的新手,已阅读 http://www.gastonsanchez.com/Handling_and_Processing_Strings_in_R.pdf 正则表达式文档。我知道之前已经发布过类似的问题,但我仍然很难弄清楚我的情况。

我有一个字符串文件名向量,尝试提取子字符串,并另存为新文件名。文件名遵循以下模式:

\w_\w_(substring to extract)_\d_\d_Month_Date_Year_Hour_Min_Sec_(AM or PM)

例如,ABC_DG_MS-15-0452-268_206_281_12_1_2017_1_53_11_PM、ABC_RE_SP56-01_A_206_281_12_1_2017_1_52_34_AM,子字符串将为 MS-15-0452-268 和 SP56-01_A

我用过

map(strsplit(filenames, '_'),3)

但失败了,因为新文件名也可能有 _。

我转向高级匹配的正则表达式,想出了这个

gsub("^[^\n]+_\d_\d_\d_\d_(AM | PM)$", "", filenames)

仍然没有得到我需要的东西。

叫我黑客吧。但如果这保证是我所有字符串的格式,那么我将只使用 strsplit 来破解名称,然后只保留我想要的:

string <- 'ABC_DG_MS-15-0452-268_206_281_12_1_2017_1_53_11_PM'
string_bits <- strsplit(string, '_')[[1]]
file_name<- string_bits[3]
file_name

[1] "MS-15-0452-268"

如果你有一个包含许多文件名的列表,你可以删除显式 [[1]] 使用 sapply() 来获取每个文件的第三个元素:

sapply(string_bits, "[[", 3)

您可以使用

filenames <- c('ABC_DG_MS-15-0452-268_206_281_12_1_2017_1_53_11_PM', 'ABC_RE_SP56-01_A_206_281_12_1_2017_1_52_34_AM')
gsub('^(?:[^_]+_){2}(.+?)_\d+.*', '\1', filenames)

产生

[1] "MS-15-0452-268" "SP56-01_A"    


这里的格局是

^             # start of the string
(?:[^_]+_){2} # not _, twice
(.+?)         # anything lazily afterwards
_\d+         # until there's _\d+
.*            # consume the rest of the string

此模式被第一个捕获的组和相关文件名所取代。