java 正则表达式检查数字中的数字是否全部相同或按顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6870494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:40:18  来源:igfitidea点击:

RegEx to check if the digits in a number are all the same or in sequence

javaregex

提问by yyy

I want to check if the user's input in the server side. If the user enters a number 111111 or 22222 which has the same numbers, and also if the input is in sequence like 12345 or 456789.

我想检查用户在服务器端的输入。如果用户输入的数字 111111 或 22222 具有相同的数字,并且输入的顺序是 12345 或 456789。

回答by Susam Pal

To match consecutive same digits:

匹配连续的相同数字:

^([0-9])*$

Note that you have to escape the backslash when you put it in a java string literal, for example,

请注意,当您将反斜杠放入 java 字符串文字时,您必须对其进行转义,例如,

"^([0-9])\1*$"

For the second one you have to explicitly make a list of consecutive digits using the |operator. The regex would be really long and nasty with as many as 10-nested parantheses. One has to generate this regex using a program. In other words, this is a wrong problem to solve using regex. It would be much simpler to write a loop and test this.

对于第二个,您必须使用|运算符明确地制作一个连续数字列表。正则表达式将非常长且令人讨厌,其中包含多达 10 个嵌套的括号。必须使用程序生成此正则表达式。换句话说,这是使用正则表达式解决的错误问题。编写一个循环并测试它会简单得多。

回答by drf

This pattern will match if the user enters the same digit:

如果用户输入相同的数字,则此模式将匹配:

^(\d)*$

\1matches the first capture group, so the pattern matches whether that first digit is repeated for the entire string.

\1匹配第一个捕获组,因此模式匹配第一个数字是否在整个字符串中重复。

The second problem (consecutive digits) is somewhat more difficult.

第二个问题(连续数字)稍微困难一些。

^(?:^(?:^(?:^(?:^0?1)?2)?3)4?)?5(?:$|6(?:$|7(?:$|8(?:$|90?))))$|
    ^(0?1)?2(?:$|3(?:$|4))|^(6?7)?8(?:$|90?)$

is one implementation, assuming three or more digits. But since the number of combinations is small, enumerating (4+ digits) is also possible:

是一种实现,假设为三位或更多位数字。但是由于组合的数量很少,枚举(4+位)也是可能的:

^(?:0?123(45?)?|1?23456?|2?34567?|3?45678?|4?56789?|(5?6)?7890?|
         (0?1)?2345678?(90$)?|1?23456789?|2?345678(90?)?)$

All this said, regular expressions don't always work well for this type of problem. A Java method to check for this sequence might be cleaner.

综上所述,正则表达式并不总是适用于此类问题。检查此序列的 Java 方法可能更简洁。

回答by JJoao

This time in perl, to explain the second case easier:

这次在 perl 中,更容易解释第二种情况:

perl -nlE 'say "BAD number" if ($_ =~ /^(\d)*$/ or "123456789" =~ /$_/)'

Explanation:

解释:

  • case 1 : input ∈ /(\d)\1*/language: already presented ($_ =~ /^(\d)\1*$/)
  • case 2 : string "123456789" matches input ("123456789" =~ /$_/)
  • 情况 1 : 输入 ∈/(\d)\1*/语言: 已经呈现 ( $_ =~ /^(\d)\1*$/)
  • 情况 2:字符串“123456789”匹配输入 ( "123456789" =~ /$_/)