2017-10-08 110 views
2

我想清理使用R中正则表达式的字符串。我想删除任何不是AlphaNumeric或标点符号的东西。删除R中字符串中的特殊字符

我使用GSUB并一直在使用

gsub("[^[:alnum:]]", " ", x) 

但这删除标点符号。有没有办法添加“[[:punct:]]”并将两者结合起来。

感谢

+4

你可以用' “[^ [:alnum:] [:PUNCT:]] +”“ - 个人而言,我会用'+'末来替代多个字符只有一个空间。 – Rentrop

+0

这是否意味着你只是想用空格char替换任何空白字符?因为'[^ [:alnum:] [:punct:]]'基本上匹配空格。 –

+0

也许你想用'gsub(“[^ A-Za-z0-9 \\ p {P}]”,“”,x,perl = TRUE)'来代替非ASCII字母/数字和标点符号(但不是符号)? –

回答

0

我觉得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" 
相关问题