user3571389
user3571389

Reputation: 335

Strings in R - Insert a desired/arbitrary digit between a string and digit

I have a character vector that looks like this:

questions <- c("question1"  "question10" "question11" "question12" 
"question13" "question14" "question15" "question16" "question17", 
"question18" "question2"  "question3"  "question4"  "question5"  "question6"  
"question7"  "question8"  "question9")

I want to insert a 0 between "question" and single digit so that the character vector looks like:

 questions <- c("question01"  "question10" "question11" "question12" 
 "question13" "question14" "question15" "question16" "question17", 
 "question18" "question02"  "question03"  "question04"  "question05"  
 "question06"  "question07"  "question08"  "question09")

Notice that string "question" associated with double digits i.e. "question10" or "question18 are unaffected.

I am new to pattern matching. I have tried the following code:

gsub(pattern = "(\\D*)(\\d{1})", replacement = "0\\1", x = mydf6$Question, perl = TRUE)

However, its not giving the desired result.

Any help would be appreciated.

Upvotes: 0

Views: 73

Answers (1)

Mako212
Mako212

Reputation: 7312

Try

gsub("(?<=[a-z])(\\d)$", "0\\1", mydf6$Question, perl = T)

This subs in a zero, but only if the string ends with a single digit, preceded by a lowercase letter.

Upvotes: 1

Related Questions