如何在单个字符串中提取以特定字符开头和结尾的子字符串?

时间:2016-08-03 23:11:21

标签: r string substring

例如,我有以下字符串:

sample = "I am a good guy; he is cool; I am a cool dude; let's do it!"

我需要找到以“我是”开头并以“;”结尾的子串所以输出应该是:

I am a good guy
I am a cool dude

有关如何在R中执行此操作的任何建议?感谢

3 个答案:

答案 0 :(得分:4)

您可以使用正则表达式。例如

regmatches(sample, gregexpr("I am [^;]+;", sample))
# [[1]]
# [1] "I am a good guy;"  "I am a cool dude;"

请注意,由于每个字符串可以有多个匹配项,因此R返回一个向量列表。当你开始研究结果时,请注意。

答案 1 :(得分:1)

这是一个字符串库解决方案:

str_match_all(sample, "I am.*?;")
#[[1]]
#     [,1]               
#[1,] "I am a good guy;" 
#[2,] "I am a cool dude;"
stringer有几个非常强大的函数来处理从字符串中分割和提取信息。

答案 2 :(得分:0)

我们可以使用str_extract_all

library(stringr)
str_extract_all(sample, "I am [^;]+(?=;)")[[1]]
#[1] "I am a good guy"  "I am a cool dude"