是否可以記下正則表達式,以便第一個$符號將被替換爲(第二個替換爲a),第三個替換爲()等?如何用偶數位置(和奇數位置)替換字符
例如,串
This is an $example$ of what I want, $ 1+1=2 $ and $ 2+2=4$.
應該成爲
This is an (example) of what I want, (1+1=2) and (2+2=4).
是否可以記下正則表達式,以便第一個$符號將被替換爲(第二個替換爲a),第三個替換爲()等?如何用偶數位置(和奇數位置)替換字符
例如,串
This is an $example$ of what I want, $ 1+1=2 $ and $ 2+2=4$.
應該成爲
This is an (example) of what I want, (1+1=2) and (2+2=4).
排序的間接解決辦法,但在某些語言中,你可以使用callback function爲repla水泥。然後,您可以循環執行該功能中的選項。這也可以用於兩個以上的選項。例如,在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).'
或者,如果這些總是成對出現的,因爲它似乎是在你的榜樣的情況下,你可以匹配之間既$
和一切,然後更換$
和重用之間的東西使用組參考\1
;但同樣,並非所有的語言都支持那些:
>>> re.sub(r"\$(.*?)\$", r"(\1)", text)
'This is an (example) of what I want, (1+1=2) and (2+2=4).'
在R,你可以使用str_replace函數,它只是取代了第一場比賽,和一個while循環來處理在同一時間對比賽的。
# 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("\\$", ")")
}
這不是最有效的解決方案,可能的,但它會經過,並貫穿整個字符串(和)代替$。
這是什麼語言?我假設這裏的'str_replace'只會替換它找到的第一個實例?您可能想要添加該信息。 –
對不起,認爲這被標記爲R.更新。 –
在JavaScript:
function replace$(str) {
let first = false;
return str.replace(/\$/, _ => (first = !first) ? '(' : ')');
}
據此間https://stackoverflow.com/a/13947249/6332575在Ruby中已經張貼解答,您可以使用
yourstring.gsub( 「$」)with_index(1){| _,我|。 i.odd? ? 「(」:「)」}
編號正則表達式用於查找模式(帶有全局標誌的一個或多個),而不是一個字符的第n個出現。你將不得不指定周圍在這裏應用一個有用的正則表達式(例如,直接在數字之前/之後的每個「$」)。您最好使用索引函數來查找某個字符所在的所有索引。 –
請添加語言標籤。 – 2017-06-03 17:34:45