在r中提取带有数字和特殊字符的字符串

Extract string with digits and special characters in r

我有一个格式为 "filename PID00-00-00""PID00-00-00" 的文件名列表。 我想提取部分文件名以创建一个 ID 列。

我目前正在使用此代码提取字符串

names(df) <- stringr::str_extract(names(df), "(?<=PID)\d+")

binded1 = rbindlist(df, idcol = "ID")%>%
  as.data.frame(binded1)

这给出了 ID 作为 PID 之后的第一组数字。例如filename PID1234-00-01 变成 ID 1234.

我还想提取第一个连字符和后面的数字。所以从 filename PID1234-00-01 我想要 1234-00.

我的 regex 应该是什么?

试试这个:

stringr::str_extract(names(df),"(?<=PID)\d{4}-\d{2}")