Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to match an ssh connection string

Tags:

regex

ssh

I'm trying in vain to write a regular expression to match valid ssh connection strings.

I really only need to recognise strings of the format:

  • user@hostname:/some/path

but it would be nice to also match an implicit home directory:

  • user@hostname:

I've so-far come up with this regex:

/^[:alnum:]+\@\:(\/[:alnum:]+)*$/

which doesn't work as intended.

Any suggestions welcome before my brain explodes and I start speaking in line noise :)


1 Answers

Your supplied regex doesn't have the hostname section. Try:

/^[:alnum:]+\@[:alnum:\.]\:(\/[:alnum:]+)*$/

or

/^[A-Za-z][A-Za-z0-9_]*\@[A-Za-z][A-Za-z0-9_\.]*\:(\/[A-Za-z][A-Za-z0-9_]*)*$/

since I don't trust alnum without double brackets.

Also, :alnum: may not give you the required range for your sections. You can have "." characters in your host name and may also need to allow for "_" characters. And it's rare I've seen usernames or hostnames start with a non-alphabetic.

Just as a side note, I try to avoid the enhanced regexes since they don't run on all regex engines (I've been using UNIX for a long time). Unfortunately that makes my regexes ungainly (see above) and not overly internationalizable. Apologies for that.

like image 173
paxdiablo Avatar answered May 14 '26 23:05

paxdiablo