JavaScript 正则表达式删除特定的连续重复字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7780794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript Regex Remove Specific Consecutive Duplicate Characters
提问by jonnyhitek
I am trying to build a regex function that will remove any non alpha numeric characters and remove all duplicate characters e.g. this : aabcd*def%gGGhhhijkklmnoP\1223would become this : abcddefgGhijklmnoPR3. I am able to remove the special characters easily but can't for the life of me work out how to remove the duplicate characters ? This is my current code for removing the special characters :
我正在尝试构建一个正则表达式函数,它将删除任何非字母数字字符并删除所有重复字符,例如:aabcd*def%gGGhhhijkklmnoP\1223将变为:abcddefgGhijklmnoPR3。我可以轻松删除特殊字符,但终生无法弄清楚如何删除重复字符?这是我当前用于删除特殊字符的代码:
var oldString = aabcd*def%gGGhhhijkklmnoP2
var filtered = oldStringt.replace(/[^\w\s]/gi, "");
How can I extend the above regex to check for duplicate characters and those duplicate characters separated by non-alphanumeric characters.
如何扩展上述正则表达式以检查重复字符和由非字母数字字符分隔的重复字符。
回答by xanatos
The regex is /[^\w\s]|(.)\1/gi
正则表达式是 /[^\w\s]|(.)\1/gi
Test here: http://jsfiddle.net/Cte94/
在这里测试:http: //jsfiddle.net/Cte94/
it uses the backreference to search for any character (.)
followed by the same character \1
它使用反向引用来搜索任何(.)
后跟相同字符的字符\1
Unless by "check for duplicate characters" you meant that aaa => a
除非“检查重复字符”是指 aaa => a
Then it's /[^\w\s]|(.)(?=\1)/gi
然后就是 /[^\w\s]|(.)(?=\1)/gi
Test here: http://jsfiddle.net/Cte94/1/
在这里测试:http: //jsfiddle.net/Cte94/1/
Be aware that both regexes don't distinguish between case. A == a
, so Aa
is a repetition. If you don't want it, take away the i
from /gi
请注意,两个正则表达式都不区分大小写。A == a
,所以Aa
是重复。如果你不想要它,把它i
从/gi
回答by Joe
\1+ is the key
\1+ 是关键
"aabcdd".replace(/(\w)+/g, function (str, match) {
return match[0]
}); // abcd
回答by hsz
Non regex version:
非正则表达式版本:
var oldString = "aabcd*def%gGGhhhijkklmnoP2";
var newString = "";
var len = oldString.length;
var c = oldString[0];
for ( var i = 1; i < len; ++i ) {
if ( c != oldString[i] ) {
newString += c;
}
c = oldString[i];
}
回答by brahmananda Kar
short and simple input=Brahmananda output:Brahmnd ref:http://jsfiddle.net/p7yu8etz/5/
简短而简单的输入 = Brahmananda 输出:Brahmnd 参考:http: //jsfiddle.net/p7yu8etz/5/
var str = "Brahmananda";
var reg = /(.)(.*?)()/g;
while (reg.test(str))
str = str.replace(reg, "");
$("div").text(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><div>