JavaScript正则表达式删除特定的连续重复字符 [英] JavaScript Regex Remove Specific Consecutive Duplicate Characters

查看:989
本文介绍了JavaScript正则表达式删除特定的连续重复字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个正则表达式函数,该函数将删除所有非字母数字字符并删除所有重复字符,例如这个: aabcd * def%gGGhhhijkklmnoP\1223 会变成这样: abcddefgGhijklmnoPR3 。我能够轻松删除特殊字符,但不能为我的生活找出如何删除重复的字符?这是我删除特殊字符的当前代码:

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\1223 would 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 :

var oldString = aabcd*def%gGGhhhijkklmnoP\122
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.

推荐答案

正则表达式是 / [^ \\\\ t] |(。) \ 1 / gi

在此测试: http://jsfiddle.net/Cte94/

它使用反向引用来搜索任何字符(。)后跟相同的字符 \1

it uses the backreference to search for any character (.) followed by the same character \1

除非检查重复的字符你的意思是 aaa => a

Unless by "check for duplicate characters" you meant that aaa => a

然后它是 / [^ \\\\ t] |(。)(?= \ 1)/ gi

在此测试: http://jsfiddle.net/Cte94/1/

请注意,两个正则表达式都不区分大小写。 A == a ,所以 Aa 是重复。如果您不想要它,请从 / gi

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

这篇关于JavaScript正则表达式删除特定的连续重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆