简体   繁体   中英

regex for replacement of specific character outside parenthesis only

I am looking for regex (preferably in R ) which can replace (any number of) specific characters say ; with say ;; but only when not present inside parenthesis () inside the text string.

Note: 1. There may be more than one replacement character present inside parenthesis too

2. There are no nested parenthesis in the data/vector

Example

  • text;othertext to be replaced with text;;othertext
  • but text;other(texttt;some;someother);more to be replaced with text;;other(texttt;some;someother);;more . (ie ; only outside () to be replaced with replacement text)

Still if some clarification is needed I will try to explain

in_vec <- c("abcd;ghi;dfsF(adffg;adfsasdf);dfg;(asd;fdsg);ag", "zvc;dfasdf;asdga;asd(asd;hsfd)", "adsg;(asdg;ASF;DFG;ASDF;);sdafdf", "asagf;(fafgf;sadg;sdag;a;gddfg;fd)gsfg;sdfa")

in_vec
#> [1] "abcd;ghi;dfsF(adffg;adfsasdf);dfg;(asd;fdsg);ag"
#> [2] "zvc;dfasdf;asdga;asd(asd;hsfd)"             
#> [3] "adsg;(asdg;ASF;DFG;ASDF;);sdafdf"           
#> [4] "asagf;(fafgf;sadg;sdag;a;gddfg;fd)gsfg;sdfa"

Expected output (calculated manually)

[1] "abcd;;ghi;;dfsF(adffg;adfsasdf);;dfg;;(asd;fdsg);;ag" 
[2] "zvc;;dfasdf;;asdga;;asd(asd;hsfd)"             
[3] "adsg;;(asdg;ASF;DFG;ASDF;);;sdafdf"            
[4] "asagf;;(fafgf;sadg;sdag;a;gddfg;fd)gsfg;;sdfa"

You can use gsub with ;(?![^(]*\\)) :

gsub(";(?![^(]*\\))", ";;", in_vec, perl=TRUE)
#[1] "abcd;;ghi;;dfsF(adffg;adfsasdf);;dfg;;(asd;fdsg);;ag"
#[2] "zvc;;dfasdf;;asdga;;asd(asd;hsfd)"                   
#[3] "adsg;;(asdg;ASF;DFG;ASDF;);;sdafdf"                  
#[4] "asagf;;(fafgf;sadg;sdag;a;gddfg;fd)gsfg;;sdfa"       

; finds ; , (?!) .. Negative Lookahead (make the replacement when it does not match), [^(] .. everything but not ( , * repeat the previous 0 to n times, \\) .. flowed by ) .

Or

gsub(";(?=[^)]*($|\\())", ";;", in_vec, perl=TRUE)
#[1] "abcd;;ghi;;dfsF(adffg;adfsasdf);;dfg;;(asd;fdsg);;ag"
#[2] "zvc;;dfasdf;;asdga;;asd(asd;hsfd)"                   
#[3] "adsg;;(asdg;ASF;DFG;ASDF;);;sdafdf"                  
#[4] "asagf;;(fafgf;sadg;sdag;a;gddfg;fd)gsfg;;sdfa"       

; finds ; , (?=) .. Positive Lookahead (make the replacement when it does match), [^)] .. everything but not ) , * repeat the previous 0 to n times, ($|\\() .. match end $ or ( .

Or using gregexpr and regmatches extracting the part between ( and ) and making the replacement in the non-matched substrings:

x <- gregexpr("\\(.*?\\)", in_vec)  #Find the part between ( and )
mapply(function(a, b) {
  paste(matrix(c(gsub(";", ";;", b), a, ""), 2, byrow=TRUE), collapse = "")
}, regmatches(in_vec, x), regmatches(in_vec, x, TRUE))
#[1] "abcd;;ghi;;dfsF(adffg;adfsasdf);;dfg;;(asd;fdsg);;ag"
#[2] "zvc;;dfasdf;;asdga;;asd(asd;hsfd)"                   
#[3] "adsg;;(asdg;ASF;DFG;ASDF;);;sdafdf"                  
#[4] "asagf;;(fafgf;sadg;sdag;a;gddfg;fd)gsfg;;sdfa"       

But all of them will work only for simple open ( close ) combinations.

Though the problem can be tackled with regex, using a simple function might be more straightforward and easier to understand.

replace_semicolons_outside_parentheses <- function(raw_string) {
    """Replace ; with ;; outside of parentheses"""

    processed_string <- ""
    n_open_parentheses <- 0

    # Loops over characters in raw_string
    for (char in strsplit(raw_string, "")[[1]]) {

        # Update the net number of open parentheses
        if (char == "(") {
            n_open_parentheses <- n_open_parentheses + 1
        } else if (char == ")") {
            n_open_parentheses <- n_open_parentheses - 1
        }

        # Replace ; with ;; outside of parentheses
        if (char == ";" && n_open_parentheses == 0) {
            processed_string <- paste0(processed_string, ";;")
        } else {
            processed_string <- paste0(processed_string, char)
        }      
    }
    return(processed_string)
}

Note that the function above also works for nested parentheses: no semicolons inside nested parentheses are replaced: The desired output can be obtained in a single line:

out_vec <- lapply(in_vec, replace_semicolons_outside_parentheses)

# 1. 'abcd;;ghi;;dfsF(adffg;adfsasdf);;dfg;;(asd;fdsg);;ag'
# 2. 'zvc;;dfasdf;;asdga;;asd(asd;hsfd)'
# 3. 'adsg;;(asdg;ASF;DFG;ASDF;);;sdafdf'
# 4. 'asagf;;(fafgf;sadg;sdag;a;gddfg;fd)gsfg;;sdfa'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM