删除第一个和第二个下划线之前和第二个下划线之后的字符提取第一个和第二个下划线之间的字符串

Remove characters before first and after second underscore extracting string between first and second underscore

我正在使用

gsub(".*_","",ldf[[j]]),1,nchar(gsub(".*_","",ldf[[j]]))-4)

创建要写入的路径和文件名。它适用于 lfd 中只有一个下划线的名称。如果文件名后面有另一个下划线,它会切断第二个下划线前面的所有内容。

我有例如: Arof_07122016_2.csv 我想要 07122016,但我得到 2。但我不明白为什么会这样。我怎样才能使用这一行只切断第一个下划线的字符并保留第二个?

正则表达式重复默认是贪心的,详见?regex:

By default repetition is greedy, so the maximal possible number of repeats is used. This can be changed to ‘minimal’ by appending ? to the quantifier. (There are further quantifiers that allow approximate matching: see the TRE documentation.)

所以你应该使用模式".*?_"。但是,gsub 将进行多次匹配,因此您最终会得到相同的结果。要补救此问题,请使用 sub,它只会进行 1 次匹配,或者通过在正则表达式中使用 ^ 来指定您要在字符串的开头进行匹配。

sub(".*?_","","Arof_07122016_2.csv")
[1] "07122016_2.csv"
gsub("^.*?_","","Arof_07122016_2.csv")
[1] "07122016_2.csv"

看来你想要

sub("^[^_]*_([^_]*).*", "\1", ldf[[j]])

regex demo

模式匹配

  • ^ - 字符串开头
  • [^_]* - _
  • 以外的 0+ 个字符
  • _ - underascxore
  • ([^_]*) - 捕获第 1 组:除 _
  • 之外的任何 0+ 个字符
  • .* - 字符串的其余部分。

替换模式中的</code>只在结果中保留捕获的值。</p> <p><a href="https://ideone.com/mQcApp" rel="noreferrer">R demo</a>:</p> <pre><code>v <- c("Arof_07122016_2.csv", "Another_99999_ccccc_2.csv") sub("^[^_]*_([^_]*).*", "\1", v) # => [1] "07122016" "99999"