Better way get negative number in a string

I need validate when exists negative numbers in the list.
I think the better way do this is using regex.

func main() {

    fmt.Println(add("-1\n,2,3"))

}

func add(numbers string) int {

    re := regexp.MustCompile("[0-9]+")

    sum := 0

    for _, i := range re.FindAllString(numbers, -1) {

        number, _ := strconv.Atoi(i)

        sum += number

    }

    return sum

}

Hi @Erison_Nicodemos,

Regexps are tricky. Your regexp would skip the minus sign, hence turning every negative number into a positive one.

I would rather split the string by comma and white space, convert each field into a number, and then test if the number is negative.

3 Likes