在R正则表达式中匹配另一个词

Matching a word after another word in R regex

我在 R 中有一个数据框,其中一列(称为 'city')包含一个文本字符串。我的目标是只提取一个词,即从文本字符串中提取城市文本。城市文本始终跟在单词 'in' 之后,例如文本可能是:

'in London'
'in Manchester'

我尝试创建一个新列 ('municipality'):

df$municipality <- gsub(".*in ?([A-Z+).*$","\1",df$city)

这给了我 'in' 之后的第一个字母,但我需要下一个单词(仅下一个单词)

然后我尝试了:

gsub(".*in ?([A-Z]\w+))")

它适用于正则表达式检查器,但不适用于 R。有人可以帮助我吗?我知道这可能很简单,但我无法破解。提前致谢。

以下正则表达式将匹配您 city 列中的第二个词:

^in\s([^ ]*).*$

这匹配单词 in 后跟单个 space,然后是任何非 space 字符的捕获组,其中包含城市名称。

示例:

df <- data.frame(city=c("in London town", "in Manchester city"))

df$municipality <- gsub("^in\s([^ ]*).*$", "\1", df$city)

> df$municipality
[1] "London"     "Manchester"

我们可以使用str_extract

library(stringr)
str_extract(df$city, '(?<=in\s)\w+')
#[1] "London"     "Manchester"