Home  >  Article  >  Java  >  Use Java regular to remove repeated characters from strings

Use Java regular to remove repeated characters from strings

高洛峰
高洛峰Original
2017-01-16 11:09:551682browse

String str = "abcdeabcdeabcdeaaaaaadddddceeeeabcccccccacadaeec";
str = str.replaceAll(reg, "");
System.out.println(str);

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

(?s) Turn on the single-line mode DOTALL and let the . sign match any character
(.) any character and capture it in the first group
(?=.*\1) This is an assertion, indicating that the following content will be any number of characters plus the first A set of captured content

Like this, if the entire formula matches, it means that the first capture group content appears at least twice in the string and is replaced with "" empty string.

After global replacement, the characters appearing in the entire string will not be repeated.

For more related articles about using Java regular to remove repeated characters in strings, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn