Search code examples
goregex-group

Regular Expression with If Else Condition


I have a problem with If Else Condition in Regex. I have a file which contains the below format. I was looking for return value to be either 0.0.985 or 3.3.5-3811. I was trying to use if else condition in regex but unable to do so, can anyone explain me while solving the problem please.

random-app-0.0.985.tgz
busy-app-7.3.1.2-3.3.5-3811-a19874elkc-123254376584.zip

Below is the Go code I am trying to use

package main

import (
    "fmt"
    "io/ioutil"
    "regexp"
)

func main(){
    content, err:= ioutil.ReadFile("version.txt")
    if err != nil{
        fmt.Println(err)
    }
    version:= string(content)
    re:= regexp.MustCompile(`(\d+).(\d+).(\d+)|(\d+).(\d+).(\d+).(\d+)`)
    result:= re.FindAllStringSubmatch(version,-1)
    for i:= range(result){
        fmt.Println(result[i][0])
    }
}

Output is coming like

0.0.985
7.3.1
2-3.3
5-3811
19874
123254376584

Solution

  • The following regexp can be used: [\d\.]+[\.-][\d]{2,}

    package main
    
    import (
        "regexp"
        "fmt"
    )
    
    func main() {
        var re = regexp.MustCompile(`(?m)[\d\.]+[\.-][\d]{2,}`)
        var str = `random-app-0.0.985.tgz
    busy-app-7.3.1.2-3.3.5-3811-a19874elkc-123254376584.zip`
        
        for i, match := range re.FindAllString(str, -1) {
            fmt.Println(match, "found at index", i)
        }
    }
    

    The output

    0.0.985 found at index 0
    3.3.5-3811 found at index 1
    

    playground

    ?m multi line modifier. Causes ^ and $ to match the begin/end of each line (not only begin/end of string). In this case it does not make to much difference. It will work without it.

    [\d\.]+ matches at least once (quantifier +) a sequence of a digit or a dot

    [\.-] matches a dot or a hypen

    [\d]{2,} matches at least two digits (quantifier {2,})