HI I want to replace a forward slash by a space, but only if it appears once.
str_replace_all( 'NOOOOO//ABCDEFGHI/asdfasd//sdkksksks', "/(?!=/)", " ")
Here I want the output to be: NOOOOO//ABCDEFGHI asdfasd//sdkksksks
HI I want to replace a forward slash by a space, but only if it appears once.
str_replace_all( 'NOOOOO//ABCDEFGHI/asdfasd//sdkksksks', "/(?!=/)", " ")
Here I want the output to be: NOOOOO//ABCDEFGHI asdfasd//sdkksksks
Try the following option with sub
:
input <- "NOOOOO//ABCDEFGHI/asdfasd//sdkksksks"
gsub("(?<!/)/(?!/)", " ", input, perl=TRUE)
[1] "NOOOOO//ABCDEFGHI asdfasd//sdkksksks"
The strategy here is to use the pattern (?<!/)/(?!/)
, which matches a single forward slash which it surrounded on both sides by anything other than another forward slash.
Instead of using lookarounds, you could make use of (*SKIP)(*FAIL) using sub
with the option perl=TRUE
to match the characters that should not be part of the match.
In this case you could match 2 or more forward slashes that should not be part of the match. After that, match a single forward slash to be replaced with a space.
/{2,}(*SKIP)(*F)|/
For example
s <- "NOOOOO//ABCDEFGHI/asdfasd//sdkksksks"
gsub("/{2,}(*SKIP)(*F)|/", " ", s, perl=TRUE)
Output
[1] "NOOOOO//ABCDEFGHI asdfasd//sdkksksks"