以数组形式检索正则表达式匹配
在 Java 中,确定给定模式是否与特定字符串匹配非常简单。然而,当处理多个匹配时,将它们收集到一个数组中可能具有挑战性。为了解决这个问题,请深入研究本指南,了解如何有效地利用正则表达式匹配。
迭代方法
要将匹配累积到数组中,请结合使用 Matcher 和String:
import java.util.regex.Matcher; import java.util.regex.Pattern; ... List<string> allMatches = new ArrayList(); Matcher m = Pattern.compile("your regular expression here") .matcher(yourStringHere); while (m.find()) { allMatches.add(m.group()); }</string>
此代码建立一个 Matcher 对象,该对象系统地查找输入字符串中的匹配子字符串。每个成功的匹配都会附加到 allMatches 列表中。最后,使用 allMatches.toArray(new String[0]) 将其转换为数组:
String[] matchesArr = allMatches.toArray(new String[0]);
用于 Lazier Matches 的自定义可迭代
或者,考虑实现惰性迭代器遍历并立即消耗匹配项,而无需不必要的操作处理:
public static Iterable<matchresult> allMatches( final Pattern p, final CharSequence input) { return new Iterable<matchresult>() { public Iterator<matchresult> iterator() { return new Iterator<matchresult>() { // Internal Matcher final Matcher matcher = p.matcher(input); // Lazy-filled MatchResult MatchResult pending; public boolean hasNext() { if (pending == null && matcher.find()) { pending = matcher.toMatchResult(); } return pending != null; } public MatchResult next() { if (!hasNext()) { throw new NoSuchElementException(); } MatchResult next = pending; pending = null; return next; } public void remove() { throw new UnsupportedOperationException(); } }; } }; }</matchresult></matchresult></matchresult></matchresult>
使用如下:
for (MatchResult match : allMatches( Pattern.compile("[abc]"), "abracadabra")) { System.out.println(match.group() + " at " + match.start()); }
以上是如何在 Java 中以数组形式高效检索所有正则表达式匹配项?的详细内容。更多信息请关注PHP中文网其他相关文章!
声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章
刺客信条阴影:贝壳谜语解决方案
3 周前ByDDD
Windows 11 KB5054979中的新功能以及如何解决更新问题
2 周前ByDDD
在哪里可以找到原子中的起重机控制钥匙卡
3 周前ByDDD
节省R.E.P.O.解释(并保存文件)
1 个月前By尊渡假赌尊渡假赌尊渡假赌
刺客信条阴影 - 如何找到铁匠,解锁武器和装甲定制
4 周前ByDDD

热工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3汉化版
中文版,非常好用

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

Atom编辑器mac版下载
最流行的的开源编辑器

禅工作室 13.0.1
功能强大的PHP集成开发环境