How to adjust regex to be usable in gsub() in R?

Viewed 41

I am looking to replace every 4th space in my ggplot label with a newline, in regex my code looks like this:

/^(?:[^\s]*[\s]){3}[^\s]*([\s])/

You can check it here: https://regex101.com/r/q7t608/1

But when i try to use this in R, using gsub() it doesn´t work.

gsub('/^(?:[^\\s]*[\\s]){3}[^\\s]*([\\s])/','\n', "trvalý pobyt na území hl. města Prahy")

[1] "trvalý pobyt na území hl. mesta Prahy"

Even thought I believe I have escaped all the \. My original data contains Czech characters that may be causing the issue so i have included them in my example.

When i try a basic example it works:

gsub('\\s','\n',"trvalý pobyt na území hl. města Prahy")

[1] "trvalý\npobyt\nna\núzemí\nhl.\nmesta\nPrahy"

Sorry if my question is basic, I have never worked with regex.

1 Answers

In case you're interested in non-regex, here's an alternative:

S <- strsplit("trvalý pobyt na území hl. m?sta Prahy", " ", fixed = TRUE)[[1]]
paste(sapply(split(S, (seq_along(S)-1) %/% 3), paste, collapse = " "), collapse = "\n")
# [1] "trvalý pobyt na\núzemí hl. m\nsta Prahy"
Related