如何在Java中使用正则表达式查找重复的字符? [英] How can I find repeated characters with a regex in Java?

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

问题描述

任何人都可以给我一个Java正则表达式来识别字符串中的重复字符吗?我只是寻找立即重复的字符,它们可以是字母或数字。

Can anyone give me a Java regex to identify repeated characters in a string? I am only looking for characters that are repeated immediately and they can be letters or digits.


abccde< - 寻找这个(立即重复c)

abccde <- looking for this (immediately repeating c's)

abcdce< - 不是这个(c被另一个字符分开)

abcdce <- not this (c's seperated by another character)


推荐答案

尝试(\\w)\\1 +

\\\\ 匹配任何单词字符(字母,数字或下划线)和 \\1 + 匹配第一组括号中的任何内容,一次或多次。所以你最终匹配任何出现的单词字符,然后立即再跟一个或多个相同的单词字符。

The \\w matches any word character (letter, digit, or underscore) and the \\1+ matches whatever was in the first set of parentheses, one or more times. So you wind up matching any occurrence of a word character, followed immediately by one or more of the same word character again.

(注意我把正则表达式作为Java字符串,即反斜杠已经翻了一倍)

(Note that I gave the regex as a Java string, i.e. with the backslashes already doubled for you)

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

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