2
我想清理使用R中正则表达式的字符串。我想删除任何不是AlphaNumeric或标点符号的东西。删除R中字符串中的特殊字符
我使用GSUB并一直在使用
gsub("[^[:alnum:]]", " ", x)
但这删除标点符号。有没有办法添加“[[:punct:]]”并将两者结合起来。
感谢
我想清理使用R中正则表达式的字符串。我想删除任何不是AlphaNumeric或标点符号的东西。删除R中字符串中的特殊字符
我使用GSUB并一直在使用
gsub("[^[:alnum:]]", " ", x)
但这删除标点符号。有没有办法添加“[[:punct:]]”并将两者结合起来。
感谢
你可以试试这个(run here):
x <- "1 [email protected]#[email protected][email protected]#[email protected]#[email protected]#! 11 ;'. R Tutorial"
gsub("[^A-Za-z0-9,;._-]","",x)
包括其他标点符号根据自己的需要
我觉得stringr和画谜是非常方便的包装打造的正则表达式
> library(stringr)
> library(rebus)
> # string
> x <- "1 [email protected]#[email protected][email protected]#[email protected]#[email protected]#! 11 ;'. R Tutorial"
>
> # define the pattern
> pat<-or(WRD,char_class(",;._-"))
> # the regex of the pattern
> pat
<regex> (?:\w|[,;._-])
> # split the string into single character
> x1<-unlist(str_split(x,""))
> # subset the character based on the pattern and collapse them
> str_c(str_subset(x1,pat),collapse = "")
[1] "111;.RTutorial"
如果您想使用t他[:PUNCT:]正则表达式
> # define the pattern using puntc
> pat2<-or(WRD,PUNCT)
> # the regex of the pattern
> pat2
<regex> (?:\w|[:punct:])
> # subset the character based on the pattern and collapse them
> str_c(str_subset(x1,pat2),collapse = "")
[1] "[email protected]#[email protected][email protected]#[email protected]#[email protected]#!11;'.RTutorial"
你可以用' “[^ [:alnum:] [:PUNCT:]] +”“ - 个人而言,我会用'+'末来替代多个字符只有一个空间。 – Rentrop
这是否意味着你只是想用空格char替换任何空白字符?因为'[^ [:alnum:] [:punct:]]'基本上匹配空格。 –
也许你想用'gsub(“[^ A-Za-z0-9 \\ p {P}]”,“”,x,perl = TRUE)'来代替非ASCII字母/数字和标点符号(但不是符号)? –