简体   繁体   中英

Extract string from Given vector string in R

I want to extract city names from all the address given in the vector. address_list=c("802/hiranandani/Mumbai", "2A/kalka-Delhi", "345#near adyar#Chennai", "10-shyaam bazzar-Kolkata")

I tried using strsplit(address_list, c("/","-","#","-"),) function. But it's not giving expected answer. Final answer should be

## [1] "Mumbai"
## [1] "Delhi"
## [1] "Chennai"
## [1] "Kolkata"

Here is a base R solution using gsub

> gsub(".*(\\b\\w+$)","\\1",address_list)
[1] "Mumbai"  "Delhi"   "Chennai" "Kolkata"

If you want to print each one, try

> for (i in gsub(".*(\\b\\w+$)","\\1",address_list)) print(i)
[1] "Mumbai"
[1] "Delhi"
[1] "Chennai"
[1] "Kolkata"

Use stringr

> library(stringr)
> str_extract(address_list, '\\w+$')
[1] "Mumbai"  "Delhi"   "Chennai" "Kolkata"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM