Kayla
Kayla

Reputation: 87

Replacing a blank space between two capital letters with an underscore

I have characters in a string that look like this:

" A E 222;CMPSC 201 orCMPSC 202" 

What I want to do is make is so that it looks like this:

" A_E_222;CMPSC_201 orCMPSC_202" 

So far I tried the following code but it only puts an underscore in front or in 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:])")

Upvotes: 3

Views: 227

Answers (1)

akrun
akrun

Reputation: 887541

We can use regex lookarounds to match space that follows a capital letter ((?<=[A-Z])) and is followed by a capital letter or number ((?=[A-Z0-9])), replace it with _

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

Upvotes: 2

Related Questions