FTP URL in GO
Match FTP and FTPS URLs, capturing optional credentials, host, port, and path.
Try it in the GO tester →Pattern
regexGO
ftps?:\/\/(?:([^:@\s]+)(?::([^@\s]*))?@)?([^:\/\s]+)(?::(\d+))?(?:\/\S*)? (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`ftps?:\/\/(?:([^:@\s]+)(?::([^@\s]*))?@)?([^:\/\s]+)(?::(\d+))?(?:\/\S*)?`)
input := `Source: ftp://anon:guest@files.example.com/pub/data.csv`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
How the pattern works
ftps?:\/\/ matches both `ftp://` and `ftps://`. The optional auth group captures user and password. The host group captures the server. (?::(\d+))? optionally captures the port (default is 21). (?:\/\S*)? optionally captures the path.
Examples
Input
Source: ftp://anon:guest@files.example.com/pub/data.csvMatches
ftp://anon:guest@files.example.com/pub/data.csv
Input
ftps://secure.host:990/privateMatches
ftps://secure.host:990/private
Input
no ftp linkNo match
—