我有一个字符串
string <- "You know that song Mary had a little lamb? Mary is my friend."
我想将它拆分为
> string[1]
[1] "You know that song "
> string[2]
[1] " had a little lamb? Mary is my friend."
我想将它拆分为“Mary”的第一个实例。
更接近我的实际问题,假设我有以下字符串:
string <- "Name: Mary
Some stuff about Mary goes here, for a page
Name: Mary
There's more stuff about her.
Name: Sue
Now the name is different. I want to split on Sue here.
Name: Sue
Sue appears again, but because the name is Sue again I don't want to splt.
Name: Beth
The name changed again, so I want to split on Beth above (following Name: ).
Name: Amy
The name changed again and now I want to split on the 'Amy' immediately following Name: ."
基本上,我想拆分此文档,以便每个元素对应于一个人的信息,以便:
> string
[1] "Name: Mary\n Some stuff about Mary goes here, for a page\n Name: Mary\n There's more stuff about her.\n Name: "
[2] "Sue\n Now the name is different. I want to split on Sue here.\n Name: Sue\n Sue appears again, but because the name is Sue again I don't want to splt.\n Name: "
[3] "Beth\n The name changed again, so I want to split on Beth above (following Name: ).\n Name: "
[4] "Amy\n The name changed again and now I want to split on the 'Amy' immediately following Name: ."
答案 0 :(得分:3)
可能有帮助
string1 <- "You know that song Mary had a little lamb? Mary is my friend and she is also a friend of another friend"
strsplit(string1, '(\\b\\S+\\b)(?=.*\\b\\1\\b.*)', perl=TRUE)[[1]]
#[1] "You know that song " " had " " little lamb? Mary "
#[4] " my " " and she is also a " " of another friend"
另一个案例
$(".toggle").hide();
$(".cancel, .contact").click(function() {
$(".toggle").slideToggle("slow");
$(".buttons").toggle();
});
注意:我不确定这是否是OP希望为第二个例子分割的方式。
答案 1 :(得分:2)
试试这个:
regmatches(string, regexpr("Mary", string), invert = TRUE)