package main
import (
"regexp"
"fmt"
)
func main() {
var re = regexp.MustCompile(`(?im)# Host entry:
# Start of line followed by optional horizontal spaces,
# The word "Host" case-insensitive, followed by anything (captured) and a new line.
^[\t ]*host[\t ]+(.+?)[\t ]*\n
# A configuration line or comment, multiple times:
(?:
# Negative lookahead to avoid matching a new "Host" entry, but
# also with optional comment lines before it.
(?!(?:^[\t ]*\#.*\n)*[\t ]*host\b)
# Optional horizontal spaces.
[\t ]*
# Config line, comment or empty line (done with the ? at the end).
(?:
# A) A config line, capturing it (with space or equal sign).
(\w+)\b(?:[\t ]*=[\t ]*|[\t ]+)(.*) |
# B) Or a comment.
\#.*
)?
# New line or end of the config file.
(?:\n|\Z)
)+`)
var str = `Host test
Hostname test.domain.com
User james
Port 22
# Comment
IdentityFile ~/.ssh/key.pub
# With 2 aliases
Host test2 test-2
Hostname test2.domain.com
User = james
Port=22
# Port 23
IdentityFile = ~/.ssh/key2.pub
# For all hosts except test2, activate compression and set log level:
Host * !test2
Compression yes
LogLevel INFO
IdentityFile ~/.ssh/id_rsa
Host *.sweet.home
Hostname 192.168.2.17
User tom
IdentityFile "~/.ssh/id tom.pub" # If has spaces, then quote it.
# With a lot of spaces between lines
Host localhost
Hostname 127.0.0.*
IdentityFile ~/.ssh/id_rsa
# Without empty lines between Host definitions:
Host dummy
Hostname ssh.dummy.com
User user
Host dummy2
Hostname ssh.dummy2.com
User user`
for i, match := range re.FindAllString(str, -1) {
fmt.Println(match, "found at index", i)
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Golang, please visit: https://golang.org/pkg/regexp/