使用 Java 模式的正则表达式匹配字符串中的四个重复字母
我想匹配 aaaa、aaaad、adjjjjk 等内容。像 ([az])\1+ 这样的东西被用来匹配重复的字符,但我无法弄清楚这四个字母。
I want to match something like aaaa, aaaad, adjjjjk. Something like ([a-z])\1+ was used to match the repeated characters, but I am not able to figure this out for four letters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您想要匹配单个字符,然后该字符再重复 3 次:
注意:在 Java 中,您需要转义正则表达式中的反斜杠。
更新:它没有执行您想要的操作的原因是因为您正在使用方法
matches
要求字符串与正则表达式完全匹配,而不仅仅是这样它包含正则表达式。要检查包含情况,您应该使用匹配器
类。这是一些示例代码:结果:
You want to match a single character and then that character repeated three more times:
Note: In Java you need to escape the backslashes inside your regular expressions.
Update: The reason why it isn't doing what you want is because you are using the method
matches
which requires that the string exactly matches the regular expression, not just that it contains the regular expression. To check for containment you should instead use theMatcher
class. Here is some example code:Result:
不了解有限重复语法,您自己的问题解决能力应该会引导您这样做:
显然这并不漂亮,但是:
问题是在Java中,
matches
需要匹配整个字符串;就好像该模式被^
和$
包围。不幸的是,没有
String.containsPattern(String regex)
,但您始终可以使用这个用.*
包围模式的技巧:Not knowing about the finite repetition syntax, your own problem solving skill should lead you to this:
Obviously it's not pretty, but:
The problem is that in Java,
matches
need to match the whole string; it is as if the pattern is surrounded by^
and$
.Unfortunately there is no
String.containsPattern(String regex)
, but you can always use this trick of surrounding the pattern with.*
:您可以将
{n}
放在某个内容后面以匹配它n
次,因此:You can put
{n}
after something to match itn
times, so:预定义重复的一般正则表达式模式是
{4}
。因此这里 ([az])\1{3} 应匹配您的 4 个字符。
General regex pattern for predefinite repetition is
{4}
.Thus here ([a-z])\1{3} should match your 4 chars.