首页 > 解决方案 > 正则表达式查找字符串是否包含 1 次或多次出现的数字 6

问题描述

我需要在Java中提出正则表达式来查找它是否在字符串中包含“6”。目前,如果我试图重申,我的表达只计算“6”的第一个实例,而忽略其他的。你能这么好心并在这里帮助我吗?

以下是我的代码:

import java.math.BigInteger;
import java.util.Scanner;
import java.util.regex.Pattern;

public class RegexTest {
  public static void main(String[] args) {

    BigInteger count = BigInteger.valueOf(0);

    Scanner s = new Scanner(System.in);
    BigInteger l = s.nextBigInteger();
    BigInteger h = s.nextBigInteger();

    BigInteger i = l;

    for (i = l; (i.compareTo(h) == -1) || (i.compareTo(h) == 0);) {
      String inputAsString = i.toString();
      if (Pattern.matches("[6]+", inputAsString)) {
        count = count.add(BigInteger.ONE);
      }
      i = i.add(BigInteger.ONE);
    }
    System.out.println("Total of 6s: " + count);
  }
}

我的代码只计算“6”,如果输入是 1 和 20,则缺少“16”。

标签: java

解决方案


您的正则表达式仅匹配单个6. 您必须在其前后添加任意字符( ) 的任意数字( *) :.

if (Pattern.matches(".*[6]+.*", inputAsString))


推荐阅读