正则表达式检查重复字符 [英] Regular Expression to check for repeating characters

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

问题描述

我必须创建一个正则表达式,它允许在 a-z、A-Z 和 0-9 范围内的文本*ALL"(大小写无关)OR 中的任何一个字符必须为 17 个字符长.我这样做没有任何问题:

I had to create a regular expression that allows in either the text "*ALL" (case independent) OR characters in the ranges a-z, A-Z and 0-9 which must be 17 characters long. This I have done without any problems:

^([\*][Aa][Ll][Ll]|[a-zA-Z0-9]{17})$

我遇到的问题是如何更改它,以便在多次输入相同的字符(例如 17 个 x)时它会出现.

The problem I am having is how to alter it so that it picks up if just the same character is entered a number of times (e.g. 17 x's).

推荐答案

为此,您需要使用捕获括号.这是一个概念,即您用括号括起来的任何内容都将被捕获到正则表达式解析器的内存中.

In order to do that you'd need to use the catching parentheses. It's a concept in which whatever you surround with parentheses will be captured into the memory of the regular expression parser.

所以如果你有以下表达式:

So if you have the following expression:

(\w)\1+

它将匹配单个单词字符:[a-zA-Z0-9_] 及其后的相同字符.因为括号捕获并记住了存储在其中的内容.

it will match a single word character: [a-zA-Z0-9_] and the same character(s) after it. Because the parentheses caught and memorised what was stored inside them.

所以在你的情况下:

^((?:\*[aA][lL]{2})|([a-zA-Z0-9])\1{17})$

其中 (?:) 是非捕获括号.

where the (?:) is a non capturing parentheses.

您也可以使用 \1{1,17} 结构,这意味着该字符应重复 1 到 17 次.

You can also use the \1{1,17} construct which means the character should be repeated from 1 to 17 times.

另外一点,我认为在这里使用正则表达式有点矫枉过正.您可能应该保存字符串,将其小写,然后将其与 '*all' 进行比较.如果它不相等,那么您可以使用正则表达式 ^([a-zA-Z0-9])\1{17}$ 以获得更多的可读性.

On another note I think that using a regular expression here is a bit overkill. You should probably save the string, lowercase it then compare it to '*all'. If it's not equal then you can use the regular expression ^([a-zA-Z0-9])\1{17}$ for A LOT more readability.

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

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