Home > Net >  Add string if the pattern matched using Regtex
Add string if the pattern matched using Regtex

Time:06-07

I have a data table and I want to add a string (FirstWord!) to one column values if the pattern (Letter digits:Letter(s)digits) matches is like below

ColName
New test defiend
G54:Y23 (matched)
test:New

The expected results would be

New test defiend
FirstWord!G54:Y23
test:New

dt[, ColName := ColName %>% str_replace('(?<=\d)\:(?=[[:upper:]])', paste0("'FirstWord!'",.))]

I don't know how to add the "FristWord!" when I find the pattern in the ColName.

CodePudding user response:

transform(df, ColName = sub("([A-Z][0-9] :[A-Z] [0-9] )", 'FirstWord!\\1', ColName))
            ColName
1  New test defiend
2 FirstWord!G54:Y23
3          test:New

CodePudding user response:

You can use sub and backreference:

sub("([A-Z] \\d :[A-Z] )", "FirstWord!\\1", txt)
[1] "ColName"    "New test defiend"  "FirstWord!G54:Y23 (matched)" "test:New" 

Here, we wrap the pattern Upper-case letter(s)digit(s):Upper-case letter(s)digit(s) into a capturing group to be able to refer to it using backreference \\1 in sub's replacement clause; there, we also add the desired "First_Word!" string.

If the pattern should not be case-sensitive, just add (?i) to the front of the pattern.

Data:

txt <- c("ColName","New test defiend","G54:Y23 (matched)","test:New")
  • Related