我见过很多次提取w/gsub
但它们主要处理从左到右或在一次出现后提取。我想从右到左匹配,数四次出现-
,匹配第 3 次和第 4 次出现之间的所有内容。
例如:
string outcome
here-are-some-words-to-try some
a-b-c-d-e-f-g-h-i f
以下是我尝试使用的一些参考资料:
在 R 中查找特殊字符的第三次出现并删除之前的所有内容 https://stackoverflow.com/questions/35088337/find-third-occurrence-of-a-special-character-and-drop-everything-before-that-in
正则表达式 - 返回第二次出现之前的所有内容 https://stackoverflow.com/questions/7449564/regex-return-all-before-the-second-occurrence
你可以使用
([^-]+)(?:-[^-]+){3}$
See regex101.com 上的演示 https://regex101.com/r/XDF50z/1/.
In
R
this could be
library(dplyr)
library(stringr)
df <- data.frame(string = c('here-are-some-words-to-try', 'a-b-c-d-e-f-g-h-i', ' no dash in here'), stringsAsFactors = FALSE)
df <- df %>%
mutate(outcome = str_match(string, '([^-]+)(?:-[^-]+){3}$')[,2])
df
并产生
string outcome
1 here-are-some-words-to-try some
2 a-b-c-d-e-f-g-h-i f
3 no dash in here <NA>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)