所有的解决方案都很好,除了应用于闭包的编程语言(如Coda, Excel,电子表格的REGEXREPLACE)。
我下面的两个原始解决方案只使用1个连接和1个正则表达式。
方法#1:查找替换值
其思想是,如果替换值不在字符串中,则附加替换值。然后,使用一个regex,我们执行所有需要的替换:
var str = "我有一只猫,一只狗,和一只山羊。";
STR = (STR +"||||猫,狗,山羊").replace(
/猫(? = [\ s \ s] *(狗))|狗(? = [\ s \ s] *(山羊))|山羊(? = [\ s \ s] *(猫 ))|\|\|\|\|.* $ / gi, " $ 1 $ 2 $ 3”);
document.body.innerHTML = str;
解释:
cat(?=[\s\S]*(dog)) means that we look for "cat". If it matches, then a forward lookup will capture "dog" as group 1, and "" otherwise.
Same for "dog" that would capture "goat" as group 2, and "goat" that would capture "cat" as group 3.
We replace with "$1$2$3" (the concatenation of all three groups), which will always be either "dog", "cat" or "goat" for one of the above cases
If we manually appended replacements to the string like str+"||||cat,dog,goat", we remove them by also matching \|\|\|\|.*$, in which case the replacement "$1$2$3" will evaluate to "", the empty string.
方法#2:查找替换对
方法#1的一个问题是它一次不能超过9个替换,这是反向传播组的最大数量。
方法#2声明不只是附加替换值,而是直接替换:
var str = "我有一只猫,一只狗,和一只山羊。";
str = (str + " | | | |,猫= >狗,狗= >山羊,山羊= >猫”).replace (
/ (\ b \ w + \ b) (? = [\ s \ s] * \ 1 =>([^,]*))|\|\|\|\|.* $ / gi, " $ 2 ");
document.body.innerHTML = str;
解释:
(str+"||||,cat=>dog,dog=>goat,goat=>cat") is how we append a replacement map to the end of the string.
(\b\w+\b) states to "capture any word", that could be replaced by "(cat|dog|goat) or anything else.
(?=[\s\S]*...) is a forward lookup that will typically go to the end of the document until after the replacement map.
,\1=> means "you should find the matched word between a comma and a right arrow"
([^,]*) means "match anything after this arrow until the next comma or the end of the doc"
|\|\|\|\|.*$ is how we remove the replacement map.