Regex 使用stringr从R中的文本字符串中提取一个或多个单词
我有以下数据框:Regex 使用stringr从R中的文本字符串中提取一个或多个单词,regex,r,stringr,Regex,R,Stringr,我有以下数据框: df <- data.frame(city=c("in London", "in Manchester city", "in Sao Paolo")) df这一行能帮你吗 unlist(lapply(strsplit(c("in London", "in Sao Paulo", "in Manchester City"), "in "), function(x) x[2])) [1] "London" "Sao Paulo" "Manche
df <- data.frame(city=c("in London", "in Manchester city", "in Sao Paolo"))
df这一行能帮你吗
unlist(lapply(strsplit(c("in London", "in Sao Paulo", "in Manchester City"), "in "), function(x) x[2]))
[1] "London" "Sao Paulo" "Manchester City"
您可以尝试以下方法:
library(stringr)
df$onlyCity <- str_extract(df$city, '[^in ](.)*')
df
city onlyCity
1 in London London
2 in Manchester city Manchester city
3 in Sao Paolo Sao Paolo
库(stringr)
df$onlyCity
假设字符串以“
中的”开头,后跟一定数量的空格(不会超过一个空格),然后是从第一个非空白字符到字符串末尾捕获的感兴趣文本。要匹配中第一个后面的所有剩余字符串,请在,你可以用
(?<=in\\s).+
(?你只是想(?为什么不干脆gsub(“^in”,”,df$city)
为了它的价值,你的正则表达式没有在“圣保罗”中选择“保罗”这是因为空格不算作单词字符,所以\\w+
到达空格时会停止。在调整空格时要小心,因为如果只允许空格,最终将捕获“曼彻斯特城”,而不仅仅是“曼彻斯特”。我还建议使用stru-match
,因为在和城市之间可能有两个空格。例如cities=stru-match(df$city,\\bin\\s+(\\p{Lu}\\p{L}*(?:\\s+\\p{Lu}\\p{L}*)
,然后城市[,2]
将保存这些值。@wiktorstribe>查看最简单的正则表达式(?
gsub("^in[ ]*(.*$)", "\\1", df$city)
[1] "London" "Manchester city" "Sao Paolo"
(?<=in\\s).+