I would need to remove all words (or replace them with spaces) in strings that have non-alphabetic characters (except hyphens and apostrophes) in the middle in R. Could anyone kindly help? Thanks.
e.g.
str = "he@llo wor*ld i'm using state-of-the-art technologies it's i4u"
expected output
" i'm using state-of-the-art technologies it's "
I have tried the following regex.
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' - "
The problem is the space between words? Tried to skip space.
gsub("\\w+[^a-z\\s'-]+\\w+", " ", lines)**
[1] "i'm" "gas-lighting" "i' -lighting" "i-love-you" " "
" " "i' - "
It wouldn't skip the spaces? Expected the following strings.
[1] "i'm" "gas-lighting" "i'm gas-lighting" "i-love-you" " "
" " "i'm gas-lighting u "
Update 2: OK, this works fine so far.
> 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" ""
Update 1: So far I am using the following regex.
> # 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 "