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,575
  • 4
  • 51
  • 82
jacky_learns_to_code
  • 826
  • 3
  • 11
  • 28

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
  • 789,025
  • 32
  • 460
  • 575