Search code examples
xmlgroovy

How to create a regular setting aside only a list of values for 3 element


I have xml that I get from the link, the problem is that I need a regular expression that will leave only a list of versions.

def listOfVersion = uc.getInputStream().text

regex = /[7]{1}\.[0-9]{1,}\..*/
println listOfVersion.findAll{it=~regex}.takeRight(3).reverse()

the output is an empty list, this is not true

<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <group>my.app</group>
  <artifact>server</artifact>
  <versioning>
    <latest>1.0.1</latest>
    <release>1.0.0</release>
    <versions>
      <version>1.0.0.2</version>
      <version>1.0.0.1</version>
      <version>1.0.0.0</version>
    </versions>
    <lastUpdated>2232323336</lastUpdated>
  </versioning>
</metadata>

conclusion

[]

you need to get a list of versions both release and just versions


Solution

  • As @Donat pointed in the comments, regex is probably not the best solution here. I would go with XML parsing using XmlSlurper. It also allows you to directly read data from your URL. As an example, try this:

    def xml = """<?xml version="1.0" encoding="UTF-8"?>
    <metadata>
      <group>my.app</group>
      <artifact>server</artifact>
      <versioning>
        <latest>1.0.1</latest>
        <release>1.0.0</release>
        <versions>
          <version>1.0.0.2</version>
          <version>1.0.0.1</version>
          <version>1.0.0.0</version>
        </versions>
        <lastUpdated>2232323336</lastUpdated>
      </versioning>
    </metadata>
    """
    
    def parsed = new XmlSlurper().parseText(xml)
    def versions = parsed.versioning.versions.version.collect { it.text() }
    println "versions: $versions"