java - 让 find() 在 java 的正则表达式中找到不止一次
问题描述
我需要 find() 多次查找。例如,在下面的正则表达式中,它只会得到“i am cool1”,但我也希望它得到“i am cool2”和“i am cool3”。我该怎么做?
Pattern pattern = Pattern.compile("i am cool([0-9]{1})", Pattern.CASE_INSENSITIVE);
String theString = "i am cool1 text i am cool2 text i am cool3 text";
Matcher matcher = pattern.matcher(theString);
matcher.find();
whatYouNeed = matcher.group(1);
解决方案
您必须为每场比赛调用 find() 。您可以使用 group() 获得整个匹配(不带索引)。
Pattern pattern = Pattern.compile("i am cool([0-9]{1})", Pattern.CASE_INSENSITIVE);
String theString = "i am cool1 text i am cool2 text i am cool3 text";
Matcher matcher = pattern.matcher(theString);
while (matcher.find()) {
System.out.println(matcher.group());
}
这将打印
i am cool1
i am cool2
i am cool3
推荐阅读
- python - 如何注释条之间的差异?
- python - Flask-WTF 表单验证失败
- dragonruby-game-toolkit - 如何使用 DragonRuby 游戏工具包中的精灵表为“精灵”设置动画?
- python - 打开 .txt 文件并创建一个新的元组集合
- php - PHP Curl 请求不适用于 easypaisa 支付网关发布请求
- php - 更新 mysql op 不与 cc-number 一起使用
- google-apps-script - 将 Google 管理员用户报告导入 Google 表格
- qt - 如何遍历 QML ListModel 的所有元素?
- javascript - 使用 REGEX 从句子开头删除不需要的字符
- flutter - 我在构建期间收到错误 setState() 或 markNeedsBuild()