如何获取R中两个单词之间的文本? [英] How to get the text between two words in R?

查看:27
本文介绍了如何获取R中两个单词之间的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取句子中两个单词之间的文本.
例如句子是 -

I am trying to get the text between two words in a sentence.
For example the sentence is -

x <-  "This is my first sentence"

现在我想要 Thisfirst 之间的文本,即 is my .我尝试了 R 中的各种函数,例如 grepgreplpmatchstr_split.但是,我无法得到我想要的.

Now I want the text between This and first which is is my . I have tried various functions from R like grep, grepl, pmatch , str_split. However, I could not get exactly what I want .

这是我使用 gsub 达到的最接近的结果.

This is the closest what I have reached with gsub.

gsub(".*This\\s*|first*", "", x)

它给出的输出是

 [1] "is my  sentence"

实际上,我需要的只是

[1] "is my"

任何帮助将不胜感激.

推荐答案

最后需要 .* 来匹配'first'之后的零个或多个字符

You need .* at the end to match zero or more characters after the 'first'

 gsub('^.*This\\s*|\\s*first.*$', '', x)
 #[1] "is my"

这篇关于如何获取R中两个单词之间的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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