Antoine
Antoine

Reputation: 119

How to replace character at even position by ( and odd position by )

Is it possible to write down a regular expression such that the first $ sign will be replaced by a (, the second with a ), the third with a (, etc ?

For instance, the string

This is an $example$ of what I want, $ 1+1=2 $ and $ 2+2=4$. 

should become

This is an (example) of what I want, ( 1+1=2 ) and ( 2+2=4). 

Upvotes: 1

Views: 1257

Answers (4)

Julian Zucker
Julian Zucker

Reputation: 564

In R, you can use str_replace, which only replaces the first match, and a while loop to deal with pairs of matches at a time.

# For str_*
library(stringr)
# For the pipes
library(magrittr)

str <- "asdfasdf $asdfa$ asdfasdf $asdf$ adsfasdf$asdf$"

while(any(str_detect(str, "\\$"))) {
   str <- str %>%
     str_replace("\\$", "(") %>%
     str_replace("\\$", ")")
}

It's not the most efficient solution, probably, but it will go through and replace $ with ( and ) through the whole string.

Upvotes: 0

sim
sim

Reputation: 21

According to an answer already posted here https://stackoverflow.com/a/13947249/6332575 in Ruby you can use

yourstring.gsub("$").with_index(1){|_, i| i.odd? ? "(" : ")"}

Upvotes: 1

user663031
user663031

Reputation:

In JavaScript:

function replace$(str) {
  let first = false;
  return str.replace(/\$/, _ => (first = !first) ? '(' : ')');
}

Upvotes: 0

tobias_k
tobias_k

Reputation: 82929

Sort of an indirect solution, but in some languages, you can use a callback function for the replacement. You can then cycle through the options in that function. This would also work with more than two options. For example, in Python:

>>> text = "This is an $example$ of what I want, $ 1+1=2 $ and $ 2+2=4$."
>>> options = itertools.cycle(["(", ")"])
>>> re.sub(r"\$", lambda m: next(options), text)
'This is an (example) of what I want, ( 1+1=2 ) and ( 2+2=4).'

Or, if those always appear in pairs, as it seems to be the case in your example, you could match both $ and everything in between, and then replace the $ and reuse the stuff in between using a group reference \1; but again, not all languages support those:

>>> re.sub(r"\$(.*?)\$", r"(\1)", text)
'This is an (example) of what I want, ( 1+1=2 ) and ( 2+2=4).'

Upvotes: 1

Related Questions