use strict;
my $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';
my $regex = qr/# 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)
)+/imxp;
if ( $str =~ /$regex/g ) {
print "Whole match is ${^MATCH} and its start/end positions can be obtained via \$-[0] and \$+[0]\n";
# print "Capture Group 1 is $1 and its start/end positions can be obtained via \$-[1] and \$+[1]\n";
# print "Capture Group 2 is $2 ... and so on\n";
}
# ${^POSTMATCH} and ${^PREMATCH} are also available with the use of '/p'
# Named capture groups can be called via $+{name}
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 Perl, please visit: http://perldoc.perl.org/perlre.html