如果我们有一个长字符串,那么我们可能想提取位于两个字符串之间的一部分字符串。例如,如果我们有一个字符串“ E-learning改变世界上的教育系统”,而我们想勇敢地提取字符串“教育系统”,那么我们必须非常小心地将字符串传递给字符串函数,您将在示例中知道这一点。使用gsub函数提取并不困难,但是我们必须确保使用正确的语法,否则结果将令人讨厌。
x1<-"E-learning changing the education system in the world" gsub(".*changing (.+) in.*", "\\1",x1) [1] "the education system" gsub(".*the (.+) system.*", "\\1",x1) [1] "education" x2<-"Nhooo helping programmers around the world" gsub(".*helping (.+) around.*", "\\1",x2) [1] "programmers" gsub(".*Nhooo (.+) programmers.*", "\\1",x2) [1] "helping" gsub(".*helping (.+) the.*", "\\1",x2) [1] "programmers around" x3<-"kindness is a mark of faith, and whoever has not kindness has not faith" gsub(".*a (.+) of.*", "\\1",x3) [1] "mark" gsub(".*and (.+) has.*", "\\1",x3) [1] "whoever has not kindness" gsub(".*has (.+) has.*", "\\1",x3) [1] "not kindness" gsub(".*has (.+) faith.*", "\\1",x3) [1] "not" gsub(".*and (.+) faith.*", "\\1",x3) [1] "whoever has not kindness has not" gsub(".*of (.+) whoever.*", "\\1",x3) [1] "faith, and" gsub(".*of (.+) and.*", "\\1",x3) [1] "faith," x4<-"直到他为他的兄弟希望他自己的一切之前,你们中没有人真正相信。" gsub(".*of (.+) truly.*", "\\1",x4) [1] "you" gsub(".*believes (.+) until.*", "\\1",x4) [1] "直到他为他的兄弟希望他自己的一切之前,你们中没有人真正相信。" gsub(".*believes (.+) for.*", "\\1",x4) [1] "until he wishes for his brother what he wishes" gsub(".*you (.+) until.*", "\\1",x4) [1] "truly believes" gsub(".*his (.+) what.*", "\\1",x4) [1] "brother" gsub(".*he (.+) for.*", "\\1",x4) [1] "wishes" gsub(".*until (.+) for.*", "\\1",x4) [1] "he wishes for his brother what he wishes" gsub(".*truly (.+) until.*", "\\1",x4) [1] "believes" gsub(".*truly (.+) what.*", "\\1",x4) [1] "believes until he wishes for his brother" gsub(".*truly (.+) for.*", "\\1",x4) [1] "believes until he wishes for his brother what he wishes" gsub(".*until (.+) what.*", "\\1",x4) [1] "he wishes for his brother" x5<-"To overcome evil with good is good, to resist evil by evil is evil." gsub(".*To (.+) with.*", "\\1",x5) [1] "overcome evil" gsub(".*good (.+) good.*", "\\1",x5) [1] "is" gsub(".*resist (.+) evil.*", "\\1",x5) [1] "evil by evil is" gsub(".*to (.+) evil.*", "\\1",x5) [1] "resist evil by evil is" gsub(".*evil (.+) evil.*", "\\1",x5) [1] "is" gsub(".*To (.+) evil.*", "\\1",x5) [1] "overcome evil with good is good, to resist evil by evil is" gsub(".*good, (.+) resist.*", "\\1",x5) [1] "to" gsub(".with (.+) is.*", "\\1",x5) [1] "To overcome evilgood is good, to resist evil by evil"