Removing all punctuation apart from single apostrophes and hyphens within words
gsub, r, regex
Solution
I think this does it:
gsub('( |^)-+|-+( |$)', '\\1', gsub("[^ [:alnum:]'-]", '', str1))
#[1] "I'm dash before word word dash in-between word two before word word just dashes between words word word"
Problem
I've asked a similar question before, but this one is much more specific and will require a different solution than the one provided previously, so I hope it's OK to post it. I need to keep only apostrophes and within-word dashes in my text (remove all other punctuation). For example, I want to get str2 from str1: ``` str1<-"I'm dash before word -word, dash &%$,. in-between word, two before word --word just dashes ------, between words word - word" str2<-"I'm dash before word word dash in-between word two before word word just dashes between words word word" ``` The solution I have so far, first removes dashes between words: `gsub(" - ", " ", str1)` and then leaves alphabetic and numeric characters plus remaining dashes `gsub("[^[:alnum:]['-]", " ", str1)` The problem is, it doesn’t remove dashes following each other, e.g. “—“ and dashes at the beginning and end of words: “-word” or “word—“