Replacing a space between two uppercase letters with an underscore

I have characters in a string that looks like this:

" A E 222;CMPSC 201 orCMPSC 202" 

      

I want to make make so that it looks like this:

" A_E_222;CMPSC_201 orCMPSC_202" 

      

So far I have tried the following code, but it only underlines the front or back, so I'm not sure what else to try.

str_replace_all(x, "([A-Z][:blank:][A-Z])", "\\1_")

str_replace_all(x, "([A-Z][:blank:][:digit:])", "([A-Z][:digit:])")

      

+3


source to share


1 answer


We can use regular expressions to match a space that follows a capital letter ( (?<=[A-Z])

) followed by a capital letter or a number ( (?=[A-Z0-9])

), replace it with_



gsub("(?<=[A-Z]) (?=[A-Z0-9])", "_", v1, perl = TRUE)
#[1] " A_E_222;CMPSC_201 orCMPSC_202"

      

+2


source







All Articles