使用stringr从R中的文本字符串中提取一个或多个单词 [英] Using stringr to extract one or multiple words from text string in R

查看:73
本文介绍了使用stringr从R中的文本字符串中提取一个或多个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

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

我正在使用 str_extract 并在单独的列中返回in"之后的单词.

I am using str_extract and return the word after 'in' in a separate column.

library(stringr)
str_extract(df$city, '(?<=in\\s)\\w+')

这在 95% 的情况下对我来说都很好.但是,在上面的Sao Paolo"这样的情况下,我的正则表达式会返回Sao"而不是城市名称.

This works fine for me in 95% of cases. However, there are cases like "Sao Paolo" above where my regex would return "Sao" rather than the city name.

有人可以帮我修改它以捕获其中之一吗:

Can someone please help me with amending it to capture either:

1) 到我从中提取的文本字符串末尾的所有内容?或

1) everything to the end of the text string I am extracting from? OR

2) 如果 'in' 后有多个单词,则将其也返回

2) where there is more than one word after 'in', then return that too

非常感谢.

推荐答案

要匹配第一个 in 后跟一个空格的字符串的所有其余部分,可以使用

To match all the rest of the string after the first in followed with a space, you can use

(?<=in\\s).+

lookbehind 匹配 in 介词后面有一个空格,但不会在匹配中返回它,因为lookbehinds 是零宽度断言.

The lookbehind matches the in preposition with a white space after it, but does not return it inside the match since lookbehinds are zero-width assertions.

这篇关于使用stringr从R中的文本字符串中提取一个或多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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