用于解析 Maven 坐标的正则表达式模式

Regex Pattern to parse Maven coordinates

我正在尝试编写一个 Regex 模式来解析 pom 文件中的 Maven 坐标。

[groupId]:[artifactId]:[type]:[?optional_field]:[version]:[compile]

1. org.eclipse.aether:aether-impl:jar:0.9.0.M2:compile
2. com.google.code.findbugs:annotations:jar:3.0.0:compile

3. org.sonatype.sisu:sisu-guice:jar:no_aop:3.1.0:compile

以上是 Maven 坐标的几个示例,请注意 1 和 2 有一个共同的模式,但 3 有一个额外的可选坐标

我需要一个正则表达式模式来仅提取 groupId、artifactId 和版本

任何人都可以提出适用于所有三种情况的适当模式

这个模式可能就是您要找的:

([\w\.]+):([\w\-]+):(\w+).*:([\w\.]+):

有3组:

  1. groupId
  2. artifactId
  3. 版本

你可以在这里测试:https://regex101.com/r/k8WDLm/1

或许可以不使用正则表达式,而是按 : 拆分并检查结果的长度。 如果有 5 个项目,则没有可选字段。如果有6项,则有一个可选字段。

例如:

String[] strings = {
    "org.eclipse.aether:aether-impl:jar:0.9.0.M2:compile",
    "com.google.code.findbugs:annotations:jar:3.0.0:compile",
    "org.sonatype.sisu:sisu-guice:jar:no_aop:3.1.0:compile"
};        

for (String string: strings) {
    String[] coll = string.split(":");
    System.out.println("groupId: " + coll[0]);
    System.out.println("artifactId: " + coll[1]);
    if (coll.length == 5) {
        System.out.println("version: " + coll[3]);
    }
    if (coll.length == 6) {
        System.out.println("version: " + coll[4]);
    }            
    System.out.println();          
}

Output Java example

我会使用 aether-api 库,因为它是 Maven 的一部分所基于的库。它可以安全地解析坐标并经过良好测试。

<dependency>
    <groupId>org.eclipse.aether</groupId>
    <artifactId>aether-api</artifactId>
    <version>1.1.0</version>
</dependency>

例如

public static void main(String[] args) {
    DefaultArtifact sisuJar = new DefaultArtifact("org.sonatype.sisu:sisu-guice:jar:no_aop:3.1.0");
    System.out.println(sisuJar.getGroupId());
    System.out.println(sisuJar.getArtifactId());
    System.out.println(sisuJar.getVersion());
    System.out.println(sisuJar.getClassifier());
    System.out.println(sisuJar.getExtension());
}

将输出:

org.sonatype.sisu
sisu-guice
3.1.0
no_aop
jar

关于日食以太的更多信息here

PS: 您提供的坐标无效。如果 Maven 尝试解析例如org.sonatype.sisu:sisu-guice:jar:no_aop:3.1.0:compile 它说:

 java.lang.IllegalArgumentException: Bad artifact coordinates 
      org.sonatype.sisu:sisu-guice:jar:no_aop:3.1.0:compile, 
      expected format is 
      <groupId>:<artifactId>[:<extension>[:<classifier>]]:<version>
at org.eclipse.aether.artifact.DefaultArtifact.<init>(DefaultArtifact.java:68)
at org.eclipse.aether.artifact.DefaultArtifact.<init>