Remove number between end of row and new space

Viewed 49

I'm trying to remove the numbers at the beginning of a row inside quotation marks.

> g<-"My name is Paul.\nI like playing football.\n\"55012\" And that's all."
> cat(g)
My name is Paul.
I like playing football.
"55012" And that's all.
> gsub("[\r\n]\"+[[:digit:]][^[[:space:]]]*"," ",g)
[1] "My name is Paul.\nI like playing football. 012\" And that's all."

This should work, but I don't know why only \n"55 is being replaced and not the entire number.

1 Answers

You closed the bracket expression with a couple of redundant [...]. [^[[:space:]]] is a sequence of [^[[:space:]] and ] patterns and matches any char other than [ and whitespace and then a ] char.

However, even that is not enough to fully fix the issue.

You may use

gsub("(^|\n)\"+[0-9]+\"+\\s*","\\1", g)

See the R demo

Pattern details

  • (^|\n) - start of string or a newline captured in Group 1 (referred to with \1 from the replacement pattern)
  • \"+ - one or more double quotes
  • [0-9]+ - 1+ digits
  • \"+ - one or more double quotes
  • \s* - 0+ whitespaces.

See the regex demo

Related