Extract Last Upper cases from a string [duplicate]

淺唱寂寞╮ 提交于 2021-01-29 09:04:02

问题


I am practicing with regular expressions in R. I would like to extract the last occurrence of two upper case letters. I tried

>str_extract("kjhdjkaYY,","[:upper:][:upper:]")
[1] "YY"

And it works perfectly fine. What if I would like to extract the last occurrence of such pattern. Example:

function("kKKjhdjkaYY,")
[1] "YY"

Thank you for your help


回答1:


We can use stri_extract_last_regex from stringi package

library(stringi)
stri_extract_last_regex("AAkjhdjkaYY,","[:upper:][:upper:]")
#[1] "YY"

Or if you want to stick with stringr, we can extract all the groups which match the pattern and then get the last one using tail

library(stringr)
tail(str_extract_all("AAkjhdjkaYY,","[:upper:][:upper:]")[[1]], 1)
#[1] "YY"


来源:https://stackoverflow.com/questions/53282070/extract-last-upper-cases-from-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!