Skip to content

🎯 ExtractVersionFromOutput

Extracts the first version number of the form X.Y.Z (optionally with a pre-release suffix) from any text output.

When to use

Use it when you have a non-standard command output or log and need to grab a version number but are unsure of the format. It uses a lenient regex match, suitable for outputs from composer, php, custom tools, and so on.

Signature

go
func ExtractVersionFromOutput(output string) (string, bool)

Parameters

ParameterTypeDescription
outputstringAny command output text

Return value

  • string: the extracted version number (for example 2.6.6 or 2.6.6-RC1); empty string when not found.
  • bool: whether a version number was successfully found.

Example

go
package main

import (
	"fmt"

	"github.com/scagogogo/composer-skills/pkg/composer"
)

func main() {
	outputs := []string{
		"Composer version 2.6.6 2024-02-22",
		"PHP 8.2.1 (cli) (built: Jan  4 2024)",
		"some random text without version",
	}

	for _, out := range outputs {
		if ver, ok := composer.ExtractVersionFromOutput(out); ok {
			fmt.Printf("Extracted version: %s\n", ver)
		} else {
			fmt.Println("Version number not found")
		}
	}
}

Advanced

  • 🔍 The regex used is (\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?), matching major.minor.patch with an optional - followed by a pre-release identifier (such as 1.2.3-beta.1). It returns the first match.
  • ⚠️ Because the regex is lenient, it may mismatch numbers in dates (for example, 2024-02-22 will not match because it does not conform to the three-segment dot-separated X.Y.Z form), but it is reliable for well-formed version output.
  • 🔗 For structured Composer version information (including major/minor/patch integers and release date), use ParseVersionOutput.
  • 📦 To extract a list of package names from output, use ExtractPackageNamesFromOutput.

Released under the MIT License