【问题标题】:Java Regex: Extracting a Version NumberJava 正则表达式:提取版本号
【发布时间】: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


    【解决方案1】:

    如果您知道结构,则不需要正则表达式:

        String line = "0=2.2.5 BUILD (tons of other junk here)";
        String versionNumber = line.split(" ", 2)[0].substring(2);
    

    【讨论】:

    • 我会寻找等号和空格的索引,并做一个子字符串。我认为这会更强大。
    • 我试过这个,因为它看起来比使用正则表达式简单得多。它工作得很好。谢谢。
    【解决方案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

    【讨论】:

      【解决方案3】:

      如果你真的在寻找一个正则表达式,虽然肯定有很多方法可以做到这一点。

      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
      

      【讨论】:

        【解决方案4】:

        有很多方法可以做到这一点。这是其中之一

        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(' ')));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-12-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-10
          • 2013-02-24
          相关资源
          最近更新 更多