1

I have string_a, such that

string_a <- " ,A thing, something, .   ."

Using regex, how can I just retain "A thing, something"?

I have tried the following and got such output:

sub("[[:punct:]]$|^[[:punct:]]","", trimws(string_a))
[1] "A thing, something, .   ."
Cath
  • 23,906
  • 5
  • 52
  • 86
jacky_learns_to_code
  • 824
  • 3
  • 11
  • 29

1 Answers1

1

We can use gsub to match one or more punctuation characters including spaces ([[:punct:] ] +) from the start (^) or | those characters until the end ($) of the string and replace it with blank ("")

gsub("^[[:punct:] ]+|[[:punct:] ]+$", "", string_a)
#[1] "A thing, something"

Note: sub will replace only a single instance

Or as @Cath mentioned [[:punct:] ] can be replaced with \\W

akrun
  • 874,273
  • 37
  • 540
  • 662