簡體   English   中英

使用正則表達式捕獲連續數字組

[英]capturing group of consecutive digits using 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);
}

}

這里的一種方法是使用外觀來確保您匹配恰好兩個六的島:

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

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

對於您提供的輸入字符串,這會找到兩個計數(兩個匹配項是字符串的開頭和結尾處的66 )。

正則表達式模式使用兩個外觀來斷言前6個之前和之后的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

你需要使用

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

請參閱正則表達式演示

在此輸入圖像描述

細節

  • (?<!6) - 在當前位置之前沒有6
  • 66 - 66子串
  • (?!6) - 在當前位置之后沒有6

請參閱Java演示

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

這沒多久就想到了。 我喜歡正則表達式,但除非真的有必要,否則我不會使用它們。 這是一個似乎有效的循環方法。

  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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM