Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R-获取第一次出现和最后一次出现之间的子字符串_R_String - Fatal编程技术网

R-获取第一次出现和最后一次出现之间的子字符串

R-获取第一次出现和最后一次出现之间的子字符串,r,string,R,String,我正在使用R中的长字符串,例如: string <- "end of section. 3. LESSONS. The previous LESSONS are very important as seen in Figure 1. This text is also important. Figure 1: Blah blah blah". 我尝试了以下操作,但它在最后一次出现“LESSONS”后返回子字符串,而不是第一次: gsub(".*LESSONS

我正在使用R中的长字符串,例如:

string <- "end of section. 3. LESSONS. The previous LESSONS are very important as seen in Figure 1. This text is also important. Figure 1: Blah blah blah".
我尝试了以下操作,但它在最后一次出现“LESSONS”后返回子字符串,而不是第一次:

gsub(".*LESSONS (.*) Figure 1.*", "\\1", string)
#[1] "are very important as seen in Figure 1. This text is also important."
还尝试了以下操作,但它在第一次出现“Figure 1”后剪切字符串,而不是最后一次:

library(qdapRegex)
ex_between(string, "LESSONS", "Figure 1")
#[[1]]
#[1] ". The previous LESSONS are very important as seen in"

我将感谢任何帮助

你们非常接近。在before
“LESSONS”
处使正则表达式非贪婪,以便与第一个正则表达式匹配

此外,这里您只能使用
sub
而不是
gsub

sub(".*?LESSONS\\.\\s*(.*) Figure 1.*", "\\1", string)
#[1] "The previous LESSONS are very important as seen in Figure 1. This text is also important."

你很接近。在before
“LESSONS”
处使正则表达式非贪婪,以便与第一个正则表达式匹配

此外,这里您只能使用
sub
而不是
gsub

sub(".*?LESSONS\\.\\s*(.*) Figure 1.*", "\\1", string)
#[1] "The previous LESSONS are very important as seen in Figure 1. This text is also important."

您可以从包
stringr
中使用
stru extract
,也可以在
中使用正向查找(?您可以从包
stringr
中使用
stru extract
以及在
(?你是最好的,罗纳克!谢谢!完成了!非常感谢。你是最好的,罗纳克!谢谢!完成了!非常感谢。谢谢!我知道<代码>斯特林格< /代码>,但没有使用这些分隔符,这是超级有用的。如果你觉得这个答案对你有用,请考虑一下投票。谢谢!我知道代码>斯特林格< <代码>,但没有使用那些分隔符。这是非常有用的。如果你觉得这个答案对你有用的话,请考虑一下投票。
str_extract(string, "(?<=LESSONS\\.\\s).*(?=\\sFigure 1)")
[1] "The previous LESSONS are very important as seen in Figure 1. This text is also important."