You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用正则表达式从Maven坐标提取groupId、artifactId与version

解决Maven坐标风格字符串的正则分组问题

你当前使用的正则表达式(.+?):(.+)((?::).+)?无法正确拆分带版本号的字符串,具体问题如下:

测试用例1:androidx.hilt:hilt-compiler
匹配结果符合预期:

  • group1: androidx.hilt
  • group2: hilt-compiler
  • group3:

测试用例2:androidx.hilt:hilt-compiler:1.2.3
实际匹配结果不符合预期:

  • group1: androidx.hilt
  • group2: hilt-compiler:1.2.3
  • group3:

期望的匹配结果:

  • group1: androidx.hilt
  • group2: hilt-compiler
  • group3: 1.2.3

正确的正则表达式

使用^(.+?):([^:]+)(?::(.+))?$即可实现预期的分组效果。

正则规则说明

  • ^ 和 $:锚定整个字符串,确保匹配完整的目标内容,避免部分匹配的情况。
  • (.+?):非贪婪匹配第一个冒号前的所有字符,对应groupId(group1)。
  • ([^:]+):匹配第二个冒号前的所有非冒号字符,对应artifactId(group2),这个规则能精准截断版本号的前缀。
  • (?::(.+))?:可选分组,匹配冒号开头的版本号部分,其中(.+)捕获版本号作为group3;?表示该分组可以不存在,对应无版本号的场景。

测试验证

测试用例1:androidx.hilt:hilt-compiler
匹配结果:

  • group1: androidx.hilt
  • group2: hilt-compiler
  • group3: (空)

测试用例2:androidx.hilt:hilt-compiler:1.2.3
匹配结果:

  • group1: androidx.hilt
  • group2: hilt-compiler
  • group3: 1.2.3

原正则问题分析

原正则中的(.+)是贪婪匹配,在处理带版本号的字符串时,正则引擎会优先让这个表达式匹配到字符串末尾——因为后面的((?::).+)?是可选分组,引擎认为不需要匹配该分组就能满足整个表达式,最终导致group2错误包含了版本号部分。

内容的提问来源于stack exchange,提问作者Arst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 16:15:43