java - 正则表达式查找字符串是否包含 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”。
解决方案
您的正则表达式仅匹配单个6
. 您必须在其前后添加任意字符( ) 的任意数字( *
) :.
if (Pattern.matches(".*[6]+.*", inputAsString))
推荐阅读
- python - Django:如何根据来自行的数据和来自另一个模型的数据将聚合字段添加到查询集中?
- laravel - Laravel 的 UploadedFile 存储方法的行为与 Storage::url 行为不对应
- android-studio - 首选项库导致 E/libc & E/Pref 错误
- lodash - 如何取消表单事件中去抖动功能的执行?
- python - 在字典列表中查找 r 平方的平均值
- javascript - Bootstrap 4.4 On Button Click:加载后更改/隐藏微调器
- python - 在 Python 终端中切片电子表格
- microsoft-teams - 自适应卡片和 Microsoft Teams:查找并显示用户名和投票
- python - 文件路径无法使用 mod 标头中的令牌打开 - 无法打开 S3 存储桶文件
- javascript - 如果我没有域,如何将 CORS 标头添加到我的 REST API?