【问题标题】:R remove non-alphanumeric symbols from a stringR从字符串中删除非字母数字符号
【发布时间】:2012-01-22 05:36:47
【问题描述】:

我有一个字符串,我想从中删除所有非字母数字符号,然后放入一个向量中。所以这个:

"This is a string.  In addition, this is a string!" 

会变成:

>stringVector1

"This","is","a","string","In","addition","this","is","a","string"

我查看了grep(),但找不到匹配的示例。有什么建议吗?

【问题讨论】:

    标签: r regex


    【解决方案1】:

    这是一个例子:

    > str <- "This is a string. In addition, this is a string!"
    > str
    [1] "This is a string. In addition, this is a string!"
    > strsplit(gsub("[^[:alnum:] ]", "", str), " +")[[1]]
     [1] "This"     "is"       "a"        "string"   "In"       "addition" "this"     "is"       "a"       
    [10] "string"  
    

    【讨论】:

    • 我注意到正则表达式的结尾方括号之间有一个空格。那是干什么用的?
    • @B.Mr.W.它保留字符串中的空格以进行拆分
    • 谢谢,最后,我并不羞于在 R 中使用正则表达式 gsub("[^[:alnum:]=\\.]", "", " Oh blah blah blah. Just be quiet!= 0.42 ") 比累积多次使用 gsub() 函数以用 "" 替换每个标点符号要好得多。
    【解决方案2】:

    处理这个问题的另一种方法

    library(stringr)
    text =  c("This is a string.  In addition, this is a string!")
    str_split(str_squish((str_replace_all(text, regex("\\W+"), " "))), " ")
    #[1] "This"     "is"       "a"        "string"   "In"       "addition" "this"     "is"       "a"        "string"  
    
    • str_replace_all(text, regex("\\W+"), " "):查找非单词字符并替换" "
    • str_squish():减少字符串中重复的空格
    • str_split(): 把一个字符串分成几块

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      • 2019-11-26
      • 2014-04-26
      • 1970-01-01
      • 2013-06-24
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多