Q:

gsub regex in R - ignore newline symbol

Here's a reproducible example
S0 <- "\n3 4 5"
S1 <- "\n3   5"

I want to use gsub and the following regex pattern (outside of R it works - tested in regex101) to return the digits. This regex should ignore \ and n whether they occur together or not.
([^\\n])(\s{1})?

I am not looking for a way to match the digits with a fundamentally different pattern - I'd like to know how to get the above pattern to work in R. The following do not work for me
gsub("([^\\\n])(\\s{1})?", "\\1", S0)
gsub("([^[\\\]n])(\\s{1})?", "\\1", S1)

The output should be
#S0 - 345
#S1 - 3 5

A:

Since you specifically want that regex to work you could match and optional \n (using (\n)?):
gsub("(\n)?([^\\n])(\\s{1})", "\\2", S0)
#[1] "345"
gsub("(\n)?([^\\n])(\\s{1})", "\\2", S1)
#[1] "3 5"

Note that you were right, if you use a regex tester like: https://regex101.com/ it works without the extra "(\n)?". However, I think in R you have to match more for capture groups to work properly.

