从R中的字符串中删除特殊字符

从R中的字符串中删除特殊字符,r,regex,gsub,R,Regex,Gsub,我正在尝试使用R中的正则表达式清理字符串。我想删除任何不是字母数字或标点符号的内容 我正在使用gsub,并且一直在使用 gsub("[^[:alnum:]]", " ", x) 但这会删除标点符号。有没有办法添加“[:punct:][]”并将两者结合起来 谢谢你可以试试这个(): x我认为stringr和rebus是构建regex非常方便的包 > library(stringr) > library(rebus) > # string > x <- "1 !@#!

我正在尝试使用R中的正则表达式清理字符串。我想删除任何不是字母数字或标点符号的内容

我正在使用gsub,并且一直在使用

gsub("[^[:alnum:]]", " ", x)
但这会删除标点符号。有没有办法添加“[:punct:][]”并将两者结合起来

谢谢你可以试试这个():


x我认为stringr和rebus是构建regex非常方便的包

> library(stringr)
> library(rebus)
> # string
> x <- "1 !@#!!@$!@#!@#!@#! 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"
>库(stringr)
>图书馆(REBS)
>#弦
>x
>#定义模式
>pat#模式的正则表达式
>拍
(?:\w |[,.|-]))
>#将字符串拆分为单个字符
>x1#根据模式对字符进行子集划分并折叠
>str_c(str_子集(x1,pat),collapse=”“)
[1] “111;.RTutorial”
如果您想使用[: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] "1!@#!!@!@#!@#!@#!11;'.RTutorial"
#使用puntc定义模式
>pat2#模式的正则表达式
>第二部分
(?:\w |[:点:)
>#根据模式对角色进行子集并折叠
>str_c(str_子集(x1,pat2),collapse=”“)
[1] “1!!!!!!!!!!11;”.虚拟现实”

你可以使用
“[^[:alnum:][:punt:][]+”
-就我个人而言,我会在结尾使用
+
将一行中的多个字符替换为一个空格。这是否意味着你只想用空格字符替换任何空格字符?因为
[^[:alnum:][:punt:][]
基本上匹配空白。也许您想使用
gsub(“[^A-Za-z0-9\\p{p}]”,x,perl=TRUE)
替换非ASCII字母/数字和标点符号(而不是符号)?
> # 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] "1!@#!!@!@#!@#!@#!11;'.RTutorial"