theneil
theneil

Reputation: 518

Insert character string between period and digit in R

I have a vector of character strings like so:

test <- c("A1.7","A1.8")

and I want to used regular expressions to insert A1c<= between the period and digit like so:

A1.A1c<=7 A1.A1c<=8

I looked through questions and found @zx8754 similar question; I tried to modify the answer posted in their question but had no luck

insert <- 'A1c<='
n <- 4
old <- test
lhs <- paste0('([[:alpha:]][[:digit:]][[:punct:]]{', n-1, '})([[:digit:]]+)$')
rhs <- paste0('\\1', insert, '\\2')
gsub(lhs, rhs, test)

Can anyone direct me as to how to correctly execute this?

Upvotes: 2

Views: 1285

Answers (2)

M--
M--

Reputation: 29119

Another pattern:

gsub("\\.(\\d+)", "\\.A1c<=\\1", test)  

    ## [1] "A1.A1c<=7" "A1.A1c<=8"

Regex Demo

Upvotes: 5

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627100

You may use

insert <- 'A1c<='
test <- c("A1.7","A1.8")
sub("(?<=\\.)(?=\\d)", insert, test, perl=TRUE)
## => A1.A1c<=7 A1.A1c<=8

See the online R demo

Details

  • (?<=\\.) - a positive lookbehind that matches a location that is immediately preceded with a dot
  • (?=\\d) - a positive lookahead that matches a location that is immediately followed with a digit.

The sub function will replace the first occurrence only, and perl=TRUE makes it possible to use the lookaround constructs in the pattern (as it is now parsed with the PCRE regex engine).

Upvotes: 3

Related Questions