R:如何使用正则表达式重新排列字符串中的元素?

时间:2017-08-08 18:18:35

标签: r regex string

我有一个字符串,它用逗号分隔编码的可变长度元素。例如:|A!B!C,=!A!B,>!A!C,<A!C|A!B!C,%!B!C,%!BC,%A!B,&AB

这些字符串包含4个|A!B!C=!A!B>!A!C<A!C)以及5个元素(|A!B!C%!B!C,{分别为{1}},%!BC%A!B

绝对顺序并不重要,但为了比较集合,我想重新排序元素,以便首先使用相同的符号,可能的顺序为&AB&,{{1 },|=,然后<

这将导致第一个字符串排列如下:>

第二个字符串为:%

目前,我通过一个非常慢的元素|A!B!C,=!A!B,<A!C,>!A!C&AB,|A!B!C,%!B!C,%!BC,%A!B strsplit重组来实现这一目标。

我希望我可以通过以下方式实现同​​样的目标:

order

1 个答案:

答案 0 :(得分:1)

不确定如何使用正则表达式执行此操作,因为它是一个复杂的search-and-replace方案。我最初的想法是沿着你的lins分裂和调整..而我提供的可能只是过于复杂而没有真正解决你的问题。我接着考虑允许不同的订单重新排序&#34;字符串...所以,如果它没有帮助我道歉。

#' The idea is to rearrange a string by providing an ordering rule.
#' @param strs The string containing the original data
#' @param rgx_order The individual characters to create the rule provided
#' in the order of the desired output
#' @param rgx_sprint This is the rule by which all ordered chars 
#' should abide, ie for this example "A punctuation or char followed by
#' anything and stopping at either a comma, or a line ending but not
#' including the seperator"
#' 
f <- function(strs = NULL, rgx_order = NULL, rgx_sprint = "\\%s(.*?)((?=,)|$)"){
        vrgx <- sprintf(rgx_sprint, rgx_order)
        fx <- function(str){
            stringi::stri_extract_all_regex(
                str, vrgx, omit_no_match = TRUE, simplify = TRUE
            ) %>% as.character() %>% .[mapply(nchar, .) > 0] %>% 
                stringi::stri_join(collapse = ",")
        }
        sapply(strs, fx, USE.NAMES = FALSE)
}

> chars <- c("|A!B!C,=!A!B,>!A!C,<A!C", "|A!B!C,%!B!C,%!BC,%A!B,&AB")
> new_order <-  c('&','|','=','<','>','%')

> f(strs = chars, rgx_order = new_order)
[1] "|A!B!C,=!A!B,<A!C,>!A!C"    "&AB,|A!B!C,%!B!C,%!BC,%A!B"