regex for preserving case pattern, capitalization

前端 未结 3 788
无人共我
无人共我 2020-12-03 23:09

Is there a regex for preserving case pattern in the vein of \\U and \\L?

In the example below, I want to convert \

3条回答
  •  长情又很酷
    2020-12-03 23:53

    This is one of those occasions when I think a for loop is justified:

    input <- rep("Here are a date, a Date, and a DATE",2)
    pat <- c("date", "Date", "DATE")
    ret <- c("month", "Month", "MONTH")
    
    for(i in seq_along(pat)) { input <- gsub(pat[i],ret[i],input) }
    input
    #[1] "Here are a month, a Month, and a MONTH" 
    #[2] "Here are a month, a Month, and a MONTH"
    

    And an alternative courtesy of @flodel implementing the same logic as the loop through Reduce:

    Reduce(function(str, args) gsub(args[1], args[2], str), 
           Map(c, pat, ret), init = input)
    

    For some benchmarking of these options, see @TylerRinker's answer.

提交回复
热议问题