使用正则表达式捕获一组连续的数字

时间:2019-04-12 17:00:14

标签: java regex

我正在尝试仅捕获彼此相邻的两个6,并使用正则表达式获取它发生了多少次,例如我们是否有794234879669786694326666976答案应该是2或它的66666应该是零并且因此,我正在使用以下代码,并通过此(66)*捕获了它,并使用matcher.groupcount()来获取发生了多少次但不起作用的信息!

package me;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class blah {

    public static void main(String[] args) {

       // Define regex to find the word 'quick' or 'lazy' or 'dog'
    String regex = "(66)*";
    String text = "6678793346666786784966";

    // Obtain the required matcher
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(text);
    int match=0;

    int groupCount = matcher.groupCount();
    System.out.println("Number of group = " + groupCount);

    // Find every match and print it
    while (matcher.find()) {

        match++;
    }
    System.out.println("count is "+match);
}

}

3 个答案:

答案 0 :(得分:4)

这里的一种方法是使用环顾四周,以确保您只匹配正好两个6的 岛:

String regex = "(?<!6)66(?!6)";
String text = "6678793346666786784966";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);

对于您提供的输入字符串,这发现计数为2(两个匹配在字符串的开头和结尾处都是66

regex模式使用两种环视方法来断言前6个之前和后6个之后的不是其他六个:

(?<!6)   assert that what precedes is NOT 6
66       match and consume two 6's
(?!6)    assert that what follows is NOT 6

答案 1 :(得分:0)

您需要使用

String regex = "(?<!6)66(?!6)";

请参见regex demo

enter image description here

详细信息

  • (?<!6)-当前位置前没有6
  • 66-66子字符串
  • (?!6)-当前位置之后没有6

请参见Java demo

String regex = "(?<!6)66(?!6)";
String text = "6678793346666786784966";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
int match=0;
while (matcher.find()) {
    match++;
}
System.out.println("count is "+match); // => count is 2

答案 2 :(得分:0)

很快就想到了。我喜欢正则表达式,但是除非确实需要,否则我不会使用它们。这是一种似乎可行的循环方法。

  char TARGET = '6';
  int GROUPSIZE = 2;
  // String with random termination character that's not a TARGET
  String s = "6678793346666786784966" + "z";

  int consecutiveCount = 0;
  int groupCount = 0;
  for (char c : s.toCharArray()) {
     if (c == TARGET) {
        consecutiveCount++;
     }
     else {
        // if current character is not a TARGET, update group count if
        // consecutive count equals GROUPSIZE
        if (consecutiveCount == GROUPSIZE) {
           groupCount++;
        }
        // in any event, reset consecutive count
        consecutiveCount = 0;
     }
  }

  System.out.println(groupCount);