问题
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