正则表达式匹配3个或更多连续顺序字符和连续相同字符

时间:2012-01-16 12:31:53

标签: java regex pattern-matching

我需要正则表达式来匹配以下情况。

  1. 3个或更多连续的连续字符/数字;例如123,abc,789,pqr等
  2. 3个或更多连续相同的字符/数字;例如111,aaa,bbb,222等

15 个答案:

答案 0 :(得分:16)

我认为你不能在第一种情况下使用正则表达式。第二种情况很简单:

Pattern pattern = Pattern.compile("([a-z\\d])\\1\\1", Pattern.CASE_INSENSITIVE);

由于\\1表示与群组1匹配的部分,因此这将匹配范围a-z或数字(\d)内的三个相同字符的任意序列。

答案 1 :(得分:7)

第二个问题:

\\b([a-zA-Z0-9])\\1\\1+\\b

<强>解释

\\b               : zero-length word boundary
  (               : start capture group 1
    [a-zA-Z0-9]   : a letter or a digit
  )               : end group
  \\1             : same character as group 1
  \\1+            : same character as group 1 one or more times
\\b               : zero-length word boundary

答案 2 :(得分:6)

我不同意,案例1可能是正则表达式,但你必须告诉它匹配的序列......这有点长而无聊:

/(abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|012|123|234|345|456|567|678|789)+/ig

http://regexr.com/3dqln

答案 3 :(得分:5)

据我所知,第一种情况确实不可能。正则表达式引擎对自然数字或字母表的顺序一无所知。但至少可以区分3个或更多数字和3个或更多字母,例如:

[a-z]{3,}|[A-Z]{3,}|\d{3,}

匹配abcdABCDE123,但与ab2dA5c412z不匹配。据此,第二种情况可以在较短的版本中正确地给出:

  (\w)\1{2,}

答案 4 :(得分:3)

  

3个或更多连续的连续字符/数字ex-123,abc,789,pqr等。

正则表达式无法实现。

  

3个或更多连续相同的字符/数字ex-111,aaa,bbb。 222等。

使用(?i)(?:([a-z0-9])\\1{2,})*的{​​{3}}。

如果要检查整个字符串,请使用pattern。要在字符串中查找匹配项,请使用Matcher.matches()

以下是一些示例代码:

final String ps = "(?i)(?:([a-z0-9])\\1{2,})*";
final String psLong =
        "(?i)\t\t\t# Case insensitive flag\n"
                + "(?:\t\t\t\t# Begin non-capturing group\n"
                + " (\t\t\t\t# Begin capturing group\n"
                + "  [a-z0-9]\t\t# Match an alpha or digit character\n"
                + " )\t\t\t\t# End capturing group\n"
                + " \\1\t\t\t\t# Back-reference first capturing group\n"
                + " {2,}\t\t\t# Match previous atom 2 or more times\n"
                + ")\t\t\t\t# End non-capturing group\n"
                + "*\t\t\t\t# Match previous atom zero or more characters\n";
System.out.println("***** PATTERN *****\n" + ps + "\n" + psLong
        + "\n");
final Pattern p = Pattern.compile(ps);
for (final String s : new String[] {"aa", "11", "aaa", "111",
        "aaaaaaaaa", "111111111", "aaa111bbb222ccc333",
        "aaaaaa111111bbb222"})
{
    final Matcher m = p.matcher(s);
    if (m.matches()) {
        System.out.println("Success: " + s);
    } else {
        System.out.println("Fail: " + s);
    }
}

输出是:

***** PATTERN *****
(?i)(?:([a-z0-9])\1{2,})*
(?i)            # Case insensitive flag
(?:             # Begin non-capturing group
 (              # Begin capturing group
  [a-z0-9]      # Match an alpha or digit character
 )              # End capturing group
 \1             # Back-reference first capturing group
 {2,}           # Match previous atom 2 or more times
)               # End non-capturing group
*               # Match previous atom zero or more characters


Fail: aa
Fail: 11
Success: aaa
Success: 111
Success: aaaaaaaaa
Success: 111111111
Success: aaa111bbb222ccc333
Success: aaaaaa111111bbb222

答案 5 :(得分:3)

谢谢大家的帮助。

对于第一种情况 - 3个或更多连续的连续字符/数字;例如123,abc,789,pqr等我使用下面的代码逻辑。请与您分享您的意见。

public static boolean validateConsecutiveSeq(String epin) {
    char epinCharArray[] = epin.toCharArray();
    int asciiCode = 0;
    boolean isConSeq = false;
    int previousAsciiCode = 0;
    int numSeqcount = 0;

    for (int i = 0; i < epinCharArray.length; i++) {
        asciiCode = epinCharArray[i];
        if ((previousAsciiCode + 1) == asciiCode) {
            numSeqcount++;
            if (numSeqcount >= 2) {
                isConSeq = true;
                break;
            }
        } else {
            numSeqcount = 0;
        }
        previousAsciiCode = asciiCode;
    }
    return isConSeq;
}

答案 6 :(得分:2)

匹配三个连续数字或字母表的正则表达式是 的 “([0-9] | [AA-ZZ])\ 1 \ 1”

答案 7 :(得分:1)

如果你有下限(3)和上限,则可以按如下方式生成regexString

public class RegexBuilder {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();

        int seqStart = 3;
        int seqEnd = 5;
        buildRegex(sb, seqStart, seqEnd);
        System.out.println(sb);
    }

    private static void buildRegex(StringBuilder sb, int seqStart, int seqEnd) {
        for (int i = seqStart; i <= seqEnd; i++) {
            buildRegexCharGroup(sb, i, '0', '9');
            buildRegexCharGroup(sb, i, 'A', 'Z');
            buildRegexCharGroup(sb, i, 'a', 'z');
            buildRegexRepeatedString(sb, i);
        }
    }

    private static void buildRegexCharGroup(StringBuilder sb, int seqLength,
            char start, char end) {
        for (char c = start; c <= end - seqLength + 1; c++) {
            char ch = c;
            if (sb.length() > 0) {
                sb.append('|');
            }
            for (int i = 0; i < seqLength; i++) {
                sb.append(ch++);
            }
        }
    }

    private static void buildRegexRepeatedString(StringBuilder sb, int seqLength) {
        sb.append('|');
        sb.append("([a-zA-Z\\d])");
        for (int i = 1; i < seqLength; i++) {
            sb.append("\\1");
        }
    }
}

<强>输出

012|123|234|345|456|567|678|789|ABC|BCD|CDE|DEF|EFG|FGH|GHI|HIJ|IJK|JKL|KLM|LMN|MNO|NOP|OPQ|PQR|QRS|RST|STU|TUV|UVW|VWX|WXY|XYZ|abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|([a-z\d])\1\1|0123|1234|2345|3456|4567|5678|6789|ABCD|BCDE|CDEF|DEFG|EFGH|FGHI|GHIJ|HIJK|IJKL|JKLM|KLMN|LMNO|MNOP|NOPQ|OPQR|PQRS|QRST|RSTU|STUV|TUVW|UVWX|VWXY|WXYZ|abcd|bcde|cdef|defg|efgh|fghi|ghij|hijk|ijkl|jklm|klmn|lmno|mnop|nopq|opqr|pqrs|qrst|rstu|stuv|tuvw|uvwx|vwxy|wxyz|([a-z\d])\1\1\1|01234|12345|23456|34567|45678|56789|ABCDE|BCDEF|CDEFG|DEFGH|EFGHI|FGHIJ|GHIJK|HIJKL|IJKLM|JKLMN|KLMNO|LMNOP|MNOPQ|NOPQR|OPQRS|PQRST|QRSTU|RSTUV|STUVW|TUVWX|UVWXY|VWXYZ|abcde|bcdef|cdefg|defgh|efghi|fghij|ghijk|hijkl|ijklm|jklmn|klmno|lmnop|mnopq|nopqr|opqrs|pqrst|qrstu|rstuv|stuvw|tuvwx|uvwxy|vwxyz|([a-z\d])\1\1\1\1

答案 8 :(得分:0)

  •   

    3个或更多连续的连续字符/数字;例如123,abc,789,pqr等。

    (?:(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){2,}\d|(?:a(?=b)|b(?=c)|c(?=d)|d(?=e)|e(?=f)|f(?=g)|g(?=h)|h(?=i)|i(?=j)|j(?=k)|k(?=l)|l(?=m)|m(?=n)|n(?=o)|o(?=p)|p(?=q)|q(?=r)|r(?=s)|s(?=t)|t(?=u)|u(?=v)|v(?=w)|w(?=x)|x(?=y)|y(?=z)){2,}[\p{Alpha}])
    

    https://regex101.com/r/5IragF/1

  •   

    3个或更多连续的相同字符/数字;例如111,aaa,bbb,222等。

    ([\p{Alnum}])\1{2,}
    

    https://regex101.com/r/VEHoI9/1

答案 9 :(得分:0)

全部放在一起:

  

([[a-zA-Z0-9])\ 1 \ 1+ |(abc | bcd | cde | def | efg | fgh | ghi | hij | ijk | jkl | klm | lmn | mno | nop | opq | pqr | qrs | rst | stu | tuv | uvw | vwx | wxy | xyz | 012 | 123 | 234 | 345 | 456 | 567 | 678 | 678 | 789)+

3个或更多连续的连续字符/数字;例如123,abc,789,pqr等。

  

(abc | bcd | cde | def | efg | fgh | ghi | hij | ijk | jkl | klm | lmn | mno | nop | opq | pqr | qrs | rst | stu | tuv | uvw | vwx | wxy | xyz | 012 | 123 | 234 | 345 | 456 | 567 | 678 | 789)+

3个或更多连续的相同字符/数字;例如111,aaa,bbb,222等。

  

([[a-zA-Z0-9])\ 1 \ 1 +

https://regexr.com/4727n

答案 10 :(得分:0)

全部放在一起:

  

([[a-zA-Z0-9])\ 1 \ 1+ |(abc | bcd | cde | def | efg | fgh | ghi | hij | ijk | jkl | klm | lmn | mno | nop | opq | pqr | qrs | rst | stu | tuv | uvw | vwx | wxy | xyz | 012 | 123 | 234 | 345 | 456 | 567 | 678 | 678 | 789)+

3个或更多连续的连续字符/数字;例如123,abc,789,pqr等。

  

(abc | bcd | cde | def | efg | fgh | ghi | hij | ijk | jkl | klm | lmn | mno | nop | opq | pqr | qrs | rst | stu | tuv | uvw | vwx | wxy | xyz | 012 | 123 | 234 | 345 | 456 | 567 | 678 | 789)+

3个或更多连续的相同字符/数字;例如111,aaa,bbb,222等。

  

([[a-zA-Z0-9])\ 1 \ 1 +

https://regexr.com/4727n

这也有效:

  

(?:( ?: 0(?= 1)| 1(?= 2)| 2(?= 3)| 3(?= 4)| 4(?= 5)| 5(?= 6) | 6(?= 7)| 7(?= 8)| 8(?= 9)){2,} \ d |(?:a(?= b)| b(?= c)| c(?= d)| d(?= e)| e(?= f)| f(?= g)| g(?= h)| h(?= i)| i(?= j)| j(?= k )| k(?= l)| l(?= m)| m(?= n)| n(?= o)| o(?= p)| p(?= q)| q(?= r) | r(?= s)| s(?= t)| t(?= u)| u(?= v)| v(?= w)| w(?= x)| x(?= y)| y(?= z)){2,} [[:alpha:]])|([a-zA-Z0-9])\ 1 \ 1 +

https://regex101.com/r/6fXC9u/1

答案 11 :(得分:0)

对于案例2,我受到regextester上一个示例的启发,并创建了以下正则表达式来匹配n相同的数字(要检查数字和字母,请用{{替换0-9 1}}):

A-Za-z0-9

答案 12 :(得分:0)

我正在与同事讨论这个问题,我们认为我们为#1提供了一个很好的解决方案。

检查 abc bcd 或...或 012 123 或什至任何数量的连续字符,请尝试:

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="main.css">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link href="https://fonts.googleapis.com/css?family=Bangers&display=swap" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
  <title>Drum Kit</title>
</head>

<body>

  <div class="container" id="app">

    <div class="intro">
      <img class="logo" src="\Drum Kit Starting Files\images\logo.png" alt="">
      <p class="start">Press the keys from 1-7 and get groovin'!</p>
      <p>But first, let me get your name:</p>
      <input class="input" v-model="name">
      <!-- Two way data binding (v-model) -->
      <input>

      <div class="message">
        <p v-if="name">This is &nbsp;</p>
        <p class="name">{{ name }} </p>
        <p v-if="name">'s&nbsp; personal drum kit!</p>
      </div>
    </div>

    <script src="main.js"></script>
</body>

</html>

此解决方案的好处是,如果要连续3个以上的字符,请将.*((a(?=b))|(?:b(?=c))|(?:c(?=d))|(?:d(?=e))|(?:e(?=f))|(?:f(?=g))|(?:g(?=h))|(?:h(?=i))|(?:i(?=j))|(?:j(?=k))|(?:k(?=l))|(?:l(?=m))|(?:m(?=n))|(?:n(?=o))|(?:o(?=p))|(?:p(?=q))|(?:q(?=r))|(?:r(?=s))|(?:s(?=t))|(?:t(?=u))|(?:u(?=v))|(?:v(?=w))|(?:w(?=x))|(?:x(?=y))|(?:y(?=z))|(?:0(?=1))|(?:1(?=2))|(?:2(?=3))|(?:3(?=4))|(?:4(?=5))|(?:5(?=6))|(?:6(?=7))|(?:7(?=8))|(?:8(?=9))){2,}.* 增加到比要检查的字符少一个。

每个组中的{2,}阻止捕获该组。

答案 13 :(得分:-1)

第一个问题请尝试这个。

如果在arg

中找到3个连续数字或字母,则

返回true

function check(value){
    for (i = 0; i <= val.length - 3; i++) {
      var s1 = val.charCodeAt(i);
      var s2 = val.charCodeAt(i + 1);
      var s3 = val.charCodeAt(i + 2);
      if (Math.abs(s1 - s2) === 1 && s1 - s2 === s2 - s3) {
        return true;
      }
    }

    return false;
}

console.log(check('Sh1ak@ki1r@100'));

答案 14 :(得分:-1)

对于第一个问题,如果您使用较少的正则表达式

,这是有效的
         containsConsecutiveCharacters(str) {
            for (let i = 0; i <= str.length - 3; i++) {
                var allthree = str[i] + str[i + 1] + str[i + 2];
                let s1 = str.charCodeAt(i);
                let s2 = str.charCodeAt(i + 1);
                let s3 = str.charCodeAt(i + 2);
                if (
                    /[a-zA-Z]+$/.test(allthree) &&
                    (s1 < s2 && s2 < s3 && s1+s2+s3-(3*s1) === 3)
                ) {
                    return true;
                }
            }
        }