如何使用正则表达式删除字符串中的重复字符? [英] How to remove duplicate characters in a string using regex?

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

问题描述

我需要替换字符串中的重复字符。我尝试使用

I need to replace the duplicate characters in a string. I tried using

outputString = str.replaceAll("(.)(?=.*\\1)", "");

这将替换重复的字符,但字符的位置会发生变化,如下所示。

This replaces the duplicate characters but the position of the characters changes as shown below.

haih



输出



output

aih

但我需要输出 hai 。这就是字符串中出现的字符的顺序不应该改变。下面给出了一些输入的预期输出。

But I need to get an output hai. That is the order of the characters that appear in the string should not change. Given below are the expected outputs for some inputs.

aaaassssddddd



输出



output

asd



输入



input

cdddddggggeeccc



输出



output

cdge

如何实现这一目标?

推荐答案

好像你的代码留下了最后一个字符,那么这个怎么样?

It seems like your code is leaving the last character, so how about this?

outputString = new StringBuilder(str).reverse().toString();
// outputString is now hiah
outputString = outputString.replaceAll("(.)(?=.*\\1)", "");
// outputString is now iah
outputString = new StringBuilder(outputString).reverse().toString();
// outputString is now hai

这篇关于如何使用正则表达式删除字符串中的重复字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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