我正在编写一个小的Java程序,它将解析Gradle构建文件以获取版本。
需要Java正则表达式模式来匹配Gradle构建文件中以“version'xxxxxxxxx'”开头的行。
以下是示例Gradle构建内容,我需要提取“'1.0-SNAPSHOT'”版本详细信息
group 'com.shan.sample.gradle'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'maven'
sourceCompatibility = 1.8
mainClassName = 'com.shan.sample.gradle.SampleProgram'
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
最佳答案
我仍然建议按行分析文件,并选择该行的第二个单词,其中第一个单词为version
。
但是,下面的这种实现将以正则表达式的方式满足您的目的。正则表达式(version ) ([A-Z0-9.'/-]+)
有两个组,第一个将捕获version
这个词,第二个将捕获版本号。因此,只需获取版本号。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String gradleFileContent = "group 'com.shan.sample.gradle'\n" +
"version '1.0-SNAPSHOT'\n" +
"\n" +
"apply plugin: 'java'\n" +
"apply plugin: 'application'\n" +
"apply plugin: 'maven'\n" +
"\n" +
"sourceCompatibility = 1.8\n" +
"\n" +
"\n" +
"mainClassName = 'com.shan.sample.gradle.SampleProgram'\n" +
"\n" +
"dependencies {\n" +
" testCompile group: 'junit', name: 'junit', version: '4.12'\n" +
"}\n";
Pattern p = Pattern.compile("(version )([A-Z0-9.'/-]+)");
Matcher m = p.matcher(gradleFileContent);
if (m.find()) {
System.out.println(m.group(2));
}
}
}
关于java - Java程序以在gradle构建文件中获取版本号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54258484/