在R regex中将一个单词匹配另一个单词 [英] Matching a word after another word in R regex

查看:53
本文介绍了在R regex中将一个单词匹配另一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dataframe in R with one column (called 'city') containing a text string. My goal is to extract only one word ie the city text from the text string. The city text always follows the word 'in', eg the text might be:

'in London'
'in Manchester'

我尝试创建一个新列(市政"):

I tried to create a new column ('municipality'):

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

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

This gives me the first letter following 'in', but I need the next word (ONLY the next word)

然后我尝试:

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

在正则表达式检查器上起作用,但在R中不起作用.有人可以帮助我.我知道这可能很简单,但我无法破解.提前致谢.

which worked on a regex checker, but not in R. Can someone please help me. I know this is probably very simple but I can't crack it. Thanks in advance.

推荐答案

我们可以使用str_extract

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

这篇关于在R regex中将一个单词匹配另一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆