B V*_*tor 4 regex string r punctuation gsub
我有一个大型数据框,其中包含一列字符串数据,当前包含一组名称,在某些情况下还包含一个电子邮件地址.我想找一个正则表达式,允许我在第二个逗号之前设置位置,在这些情况下使用电子邮件地址,然后删除后面的内容,以便我留下一个名字的"作者"列,不包括电子邮件.
> author<-c("Doe, Jane", "Smith, John", "Doe, John, johndoe@xyz.net", "Smith, Jane")
> ID<- c(1:4)
> df<-cbind(author, ID)
> df
author ID
[1,] Doe, Jane 1
[2,] Smith, John 2
[3,] Doe, John, johndoe@xyz.net 3
[4,] Smith, Jane 4
Run Code Online (Sandbox Code Playgroud)
我希望输出看起来如下
>df
author ID
[1,] Doe, Jane 1
[2,] Smith, John 2
[3,] Doe, John 3
[4,] Smith, Jane 4
Run Code Online (Sandbox Code Playgroud)
使用sub功能.[^,]*匹配任何字符,但不匹配,零次或多次.
> author<-c("Doe, Jane", "Smith, John", "Doe, John, johndoe@xyz.net", "Smith, Jane")
> sub("^([^,]*,[^,]*),.*", "\\1", author)
[1] "Doe, Jane" "Smith, John" "Doe, John" "Smith, Jane"
> ID<- c(1:4)
> df<-cbind(author=sub("^([^,]*,[^,]*),.*", "\\1", author), ID)
> df
author ID
[1,] "Doe, Jane" "1"
[2,] "Smith, John" "2"
[3,] "Doe, John" "3"
[4,] "Smith, Jane" "4"
Run Code Online (Sandbox Code Playgroud)
说明:
^ 断言我们刚开始.([^,]*,[^,]*),(...)称为捕获组,用于捕获与捕获组内部存在的模式匹配的那些字符.在我们的例子中,捕获组内存在的模式是[^,]*,[^,]*.我已经提到过,这[^,]*匹配任何字符,但不是逗号,零次或多次.因此[^,]*,[^,]*匹配从开始到达第二个逗号的所有字符.([^,]*,[^,]*)捕获那些匹配的字符并将其存储到组索引1中.我们可以通过指定它的索引号来引用捕获组内存在的字符.这称为反向引用.,.* 现在,这匹配第二个逗号和以下零个或多个字符.sub和gsub函数将用替换部分中提到的字符串替换所有匹配的字符.所以在我们的例子中,所有匹配的字符都被组索引1中的字符替换.这就是我们\\1在替换部分中使用的原因.