如果字符串只包含重复字符,那么查找正则表达式是什么? [英] What is a regular expression to find if string contains only repeating characters?
本文介绍了如果字符串只包含重复字符,那么查找正则表达式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经完成了:
正则表达式使用Java模式匹配字符串中的四个重复字母
和
正则表达式匹配任何重复超过10次的角色
但它们在我的情况下没用。如果我只想检查一个字符串是否包含重复的字符(如1111,abccccd,12aaaa3b等),它们就可以了。我想要的是检查字符串是否完全由重复字符组成,即aabb111,1111222,11222aaa等。
But they aren't useful in my case. They are fine if I just want to check if a string is containing repeated characters (like 1111, abccccd, 12aaaa3b, etc.). What I want is to check if string is comprising entirely of repeated characters only i.e. aabb111, 1111222, 11222aaa, etc.
任何人都可以帮我解决这个问题吗?
Can anyone help me out with this?
推荐答案
使用((。)\ + + +)+
作为模式:
String pattern = "((.)\\2+)+";
System.out.println("a".matches(pattern)); // false
System.out.println("1aaa".matches(pattern)); // false
System.out.println("aa".matches(pattern)); // true
System.out.println("aabb111".matches(pattern)); // true
System.out.println("1111222".matches(pattern)); // true
System.out.println("11222aaa".matches(pattern)); // true
System.out.println("etc.".matches(pattern)); // false
关于模式:
-
(...)
:将匹配的部分捕获为组。 (从1开始)
(...)
: capture matched part as group. (starting from 1)
((.)\2+)+
^^
|+----- group 2
+----- group 1
(。)
:匹配任何字符(换行符除外)并将其捕获为 2 组(因为它在括号后面)。 \2
:对匹配组的反向引用。如果(。)
匹配字符 x
, \2
匹配另一个 x
(不是任何字符,但只有 x
)。 PATTERN +
:匹配PATTERN的一个或多个匹配项。(。)\ + + + / code>:匹配重复字符贪婪。
(.)
: match any character (except newline) and capture it as group 2 (because it come after enclosing parenthesis).\2
: backreference to the matched group. If (.)
matched a character x
, \2
matches another x
(not any character, but only x
).PATTERN+
: matches one or more matches of PATTERN.(.)\2+
: match repeating characters greedy.这篇关于如果字符串只包含重复字符,那么查找正则表达式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文