【发布时间】:2013-06-11 19:18:33
【问题描述】:
我有一个程序将版本号存储在文件系统上的文本文件中。我在java中导入文件,我想提取版本号。我不太擅长正则表达式,所以希望有人能提供帮助。
文本文件如下所示:
0=2.2.5 BUILD (tons of other junk here)
我想提取2.2.5。没有其他的。有人可以帮我使用正则表达式吗?
【问题讨论】:
标签: java regex numbers version extract
我有一个程序将版本号存储在文件系统上的文本文件中。我在java中导入文件,我想提取版本号。我不太擅长正则表达式,所以希望有人能提供帮助。
文本文件如下所示:
0=2.2.5 BUILD (tons of other junk here)
我想提取2.2.5。没有其他的。有人可以帮我使用正则表达式吗?
【问题讨论】:
标签: java regex numbers version extract
如果您知道结构,则不需要正则表达式:
String line = "0=2.2.5 BUILD (tons of other junk here)";
String versionNumber = line.split(" ", 2)[0].substring(2);
【讨论】:
这个正则表达式应该可以解决问题:
(?<==)\d+\.\d+\.\d+(?=\s*BUILD)
试一试:
String s = "0=2.2.5 BUILD (tons of other junk here)";
Pattern p = Pattern.compile("(?<==)\\d+\\.\\d+\\.\\d+(?=\\s*BUILD)");
Matcher m = p.matcher(s);
while (m.find())
System.out.println(m.group());
2.2.5
【讨论】:
如果你真的在寻找一个正则表达式,虽然肯定有很多方法可以做到这一点。
String line = "0=2.2.5 BUILD (tons of other junk here)";
Matcher matcher = Pattern.compile("^\\d+=((\\d|\\.)+)").matcher(line);
if (matcher.find())
System.out.println(matcher.group(1));
输出:
2.2.5
【讨论】:
有很多方法可以做到这一点。这是其中之一
String data = "0=2.2.5 BUILD (tons of other junk here)";
Matcher m = Pattern.compile("\\d+=(\\d+([.]\\d+)+) BUILD").matcher(data);
if (m.find())
System.out.println(m.group(1));
如果您确定data 包含版本号,那么您也可以
System.out.println(data.substring(data.indexOf('=')+1,data.indexOf(' ')));
【讨论】: