如何删除R中包含任何非字母字符(连字符和撇号除外)的单词

时间:2019-01-27 03:08:23

标签: r regex

我需要删除R中间具有非字母字符(连字符和撇号除外)的字符串中的所有单词(或用空格替换)。有人可以提供帮助吗?谢谢。

例如
str = "he@llo wor*ld i'm using state-of-the-art technologies it's i4u"
预期产量 " i'm using state-of-the-art technologies it's "




我已经尝试过以下正则表达式。

lines <- c("i'm",
           'gas-lighting',
           "i'm gas-lighting",
           "i-love-you",
           "i@u",
           "b2b",
           "i'm gas-lighting u i@u b2b")
gsub("\\w+[^a-z'-]+\\w+", " ", lines) 
[1] "i'm"          "gas-lighting" "i' -lighting" "i-love-you"   " "            
" "            "i' -     "

问题在于单词之间的间隔?试图跳过空间。

gsub("\\w+[^a-z\\s'-]+\\w+", " ", lines)**  
[1] "i'm"          "gas-lighting" "i' -lighting" "i-love-you"   " "            
" "            "i' -     "

它不会跳过空格吗?预期以下字符串。

[1] "i'm"          "gas-lighting" "i'm gas-lighting" "i-love-you"   " "            
" "            "i'm gas-lighting u    "




更新2:好的,到目前为止工作正常。

> lines <- c("i'm",
+            'gas-lighting',
+            "i'm gas-lighting",
+            "i-love-you",
+            "i@u",
+            "b2b",
+            "i'm gas-lighting u and you and you i@u b2b",
+            " he@llo wor$ld how*are&you ")
>
> # split a string at spaces then remove the words 
> # that contain any non-alphabetic characters (excpet "-", "'")
> # then paste them together (separate them with spaces)
> unlist(lapply(lines, function(line){
+   words <- unlist(strsplit(line, "\\s+"))
+   words <- words[!grepl("[^a-z'-]", words, perl=TRUE)]
+   paste(words, collapse=" ")}))
[1] "i'm"                                "gas-lighting"                      
[3] "i'm gas-lighting"                   "i-love-you"                        
[5] ""                                   ""                                  
[7] "i'm gas-lighting u and you and you" "" 

更新1:到目前为止,我正在使用以下正则表达式。

> # replace word at the beginning of a string
> lines <- gsub("^\\s*\\w*[^a-z'-]+\\w*", " ", lines); lines
[1] "i'm"                     "gas-lighting"            "i'm gas-lighting"        "i-love-you"             
[5] " "                       " "                       "i'm gas-lighting u i@u "
> # replace word at the end of a string
> lines <- gsub("\\s[a-z]+[^a-z'-]+\\w*$", " ", lines); lines 
[1] "i'm"                     "gas-lighting"            "i'm gas-lighting"        "i-love-you"             
[5] " "                       " "                       "i'm gas-lighting u i@u "
> # replace words between spaces
> gsub("\\s\\w*[^a-z'-]+\\w*\\s", " ", lines)
[1] "i'm"                 "gas-lighting"        "i'm gas-lighting"    "i-love-you"          " "                  
[6] " "                   "i'm gas-lighting u "

2 个答案:

答案 0 :(得分:0)

我想出了一种间接的方法,但是它起作用了。

O(n)

答案 1 :(得分:0)

Harro Cyranka和grepl的变体

paste0(sapply(break_1, function(x) x[!grepl("[^Aa-zZ|'|-]", x)]), collapse = " ")