re = /^[\t ]*host[\t ]+(.+?)[\t ]*\n(?:(?!(?:^[\t ]*#.*\n)*[\t ]*host\b)[\t ]*(?:(\w+)\b(?:[\t ]*=[\t ]*|[\t ]+)(.*)|#.*)?(?:\n|\Z))+/im
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'
# Print the match result
str.scan(re) do |match|
puts match.to_s
end
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 Ruby, please visit: http://ruby-doc.org/core-2.2.0/Regexp.html