gpt4 book ai didi

regex - 根据匹配的模式替换匹配项

转载 作者:行者123 更新时间:2023-12-04 04:29:50 24 4
gpt4 key购买 nike

给定一组正则表达式,是否有一种简单的方法可以匹配多个模式,并根据匹配的模式替换匹配的文本?

例如,对于以下数据x,每个元素都以数字或字母开头,并以数字或字母结尾。我们将这些模式称为num_num(用于以数字开头,以数字结尾),num_let(以数字开头,以字母结尾),let_numlet_let

x <- c('123abc', '78fdsaq', 'aq12111', '1p33', '123', 'pzv')
type <- list(
num_let='^\\d.*[[:alpha:]]$',
num_num='^\\d(.*\\d)?$',
let_num='^[[:alpha:]].*\\d$',
let_let='^[[:alpha:]](.*[[:alpha:]])$'
)

要使用其后的模式名称替换每个字符串,我们可以执行以下操作:
m <- lapply(type, grep, x)
rep(names(type), sapply(m, length))[order(unlist(m))]
## [1] "num_let" "num_let" "let_num" "num_num" "num_num" "let_let"

有没有更有效的方法?
gsubfn

我知道,使用 gsubfn我们可以同时替换不同的匹配项,例如:
library(gsubfn)
gsubfn('.*', list('1p33'='foo', '123abc'='bar'), x)
## [1] "bar" "78fdsaq" "aq12111" "foo" "123" "pzv"

但是我不确定是否可以根据匹配的模式而不是匹配项本身来进行替换。
stringr
str_replace_all在此示例中不能很好地发挥作用,因为将匹配项迭代地替换为模式,因此最终所有内容都被 let_let覆盖:
library(stringr)
str_replace_all(x, setNames(names(type), unlist(type)))
## [1] "let_let" "let_let" "let_let" "let_let" "let_let" "let_let"

重新排序 type以便相应于 let_let的模式出现首先解决了这个问题,但是需要这样做使我感到紧张。
type2 <- rev(type)
str_replace_all(x, setNames(names(type2), unlist(type2)))
## [1] "num_let" "num_let" "let_num" "num_num" "num_num" "let_let"

最佳答案

纵梁

如果我们更改替换项,则可以使用str_replace_all,以使它们不再与任何正则表达式匹配,然后添加其他替换项以将其恢复为原始格式。例如

library(stringr)
type2 <- setNames(c(str_replace(names(type), "(.*)", "__\\1__"), "\\1"),
c(unlist(type), "^__(.*)__$"))
str_replace_all(x, type2)
## [1] "num_let" "num_let" "let_num" "num_num" "num_num" "let_let"

格雷普和提迪尔

另一种方法是先匹配然后替换,一种方法是使用 grepltidyr
library(plyr)
library(dplyr)
library(tidyr)

out <- data.frame(t(1*aaply(type, 1, grepl, x)))

out[out == 0] <- NA
out <- out %>%
mutate(id = 1:nrow(.)) %>%
gather(name,value, -id, na.rm = T) %>%
select(name)
as.character(out[,1])
## [1] "num_let" "num_let" "num_num" "num_num" "let_num" "let_let"

尽管这种方法看起来效率不高,但可以轻松找到匹配项多于或少于一个的行。

据我了解,替代匹配是在pcre2中实现的,我相信可以在正则表达式中直接解决此类问题。不幸的是,似乎还没有人为R构建pcre2软件包。

关于regex - 根据匹配的模式替换匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34688853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com