正则表达式,用于使用R
我正在使用R,并希望使用正则表达式从完整引用中创建一个in-text。例如,我有:正则表达式,用于使用R,r,regex,R,Regex,我正在使用R,并希望使用正则表达式从完整引用中创建一个in-text。例如,我有: Ali, D. A., Deininger, K., & Goldstein, M. (2014). Environmental and gender impacts of land tenure regularization in Africa: Pilot evidence from Rwanda. Journal of Development Economics, 110, 262–275.
Ali, D. A., Deininger, K., & Goldstein, M. (2014). Environmental and gender
impacts of land tenure regularization in Africa: Pilot evidence from Rwanda.
Journal of Development Economics, 110, 262–275.
我想要一个正则表达式,它将所有信息拉到第一个4位数字,包括并列词。像这样:
Ali, D. A., Deininger, K., & Goldstein, M. (2014)
有什么建议吗?谢谢 我们可以使用
sub
sub("^(.*\\(\\d{4}\\)).*", "\\1", txt)
#[1] "Ali, D. A., Deininger, K., & Goldstein, M. (2014)"
或者另一种方法是获取4位数字出现的第一个匹配的索引,然后执行
substr
i1 <- regexpr("(?<=\\()\\d{4}(?=\\))", txt, perl = TRUE)
substr(txt, seq(i1), i1+ attr(i1, "match.length"))
#[1] "Ali, D. A., Deininger, K., & Goldstein, M. (2014)"
i1您当前的方法有什么问题?@WiktorStribiżew,我看不到问题重复出现。你能指出它,我会做必要的编辑吗?这个[^(]
不是一个好主意,akrun。如果在第一个(4位数字)之前有一个(
)。现在,“^(.\\\\\\(\\d{4}\\).*”
将匹配最后出现的(4位数字)而“\\d{4}”
实际上不匹配(4位数字)但是只有4个数字。看起来你把解决方案复杂化了,特别是带有sub
的解决方案。如果你说的是第二个解决方案,我想我没有具体说明。更正