java - 如何知道正则表达式的哪一部分匹配?
问题描述
正则表达式=(i.*d.*n.*t.*)|(p.*r.*o.*f.*)|(u.*s.*r.*)
要匹配的字符串=profile
现在正则表达式将与字符串匹配。但我想知道哪个部分匹配。
意思是,我想要 (p.*r.*o. f. ) 作为输出
我怎样才能在 Java 中做到这一点?
解决方案
您可以检查哪个组匹配:
Pattern p = Pattern.compile("(i.*d.*n.*t.*)|(p.*r.*o.*f.*)|(u.*s.*r.*)");
Matcher m = p.matcher("profile");
m.find();
for (int i = 1; i <= m.groupCount(); i++) {
System.out.println(i + ": " + m.group(i));
}
将输出:
1: null
2: profile
3: null
因为第二行不为空,所以它(p.*r.*o.*f.*)
与字符串匹配。
推荐阅读
- json - 如何在ansible中将字典或列表转换为字符串
- github - 如何让dependabot仅触发安全更新
- javascript - 为可以将文件夹归档为 ZIP 以供下载的 ftp 文件服务器创建 Web UI
- angular - 使用 PDFtron Webviewer 库从 Microsoft Office PowerPoint 文件中提取注释
- xml - 【Jmeter XML】这个属性是怎么生成的?(在ResponseAssertion元素中有一个动态的prop)
- gremlin - 不使用联合的具有可变边缘深度的 Gremlin 查询
- r - gganimate:具有不同几何形状和时间点的两层
- css - 如何为 R Shiny 中的列设置小数宽度?
- javascript - VueJS 嵌套组件在 NPM 包中失败
- javascript - 将多个Word文件合并为一个