Developer

Regular expression

/^ssh-(?:rsa|ed25519)\s+[A-Za-z0-9+/=]+(?:\s+.*)?$/

Pattern breakdown

PartMeaning
Anchor or contextUse anchors when you need whole-string validation.
Main tokenThe core token sequence describes the accepted text shape.
Character classCharacter classes limit which characters are valid.
QuantifierQuantifiers control how many characters or groups are accepted.
FlagsUse language-specific flags such as i, m, or u only when needed.

Should match

  • ssh-ed25519 AAAAC3Nza user
  • ssh-ed25519AAAAC3Nzauser

Should not match

  • PRIVATE KEY
  • not matching sample
  • ssh-ed25519 AAAAC3Nza user invalid
  • PRIVATE KEYssh-ed25519 AAAAC3Nza user

Test cases

InputExpectedWhy it matters
ssh-ed25519 AAAAC3Nza userMatchRepresentative valid input for this pattern.
ssh-ed25519AAAAC3NzauserMatchRepresentative valid input for this pattern.
PRIVATE KEYNo matchCommon invalid or boundary input.
(empty string)No matchCommon invalid or boundary input.
not matching sampleNo matchCommon invalid or boundary input.
ssh-ed25519 AAAAC3Nza user invalidNo matchCommon invalid or boundary input.
PRIVATE KEYssh-ed25519 AAAAC3Nza userNo matchCommon invalid or boundary input.

JavaScript

const re = /^ssh-(?:rsa|ed25519)\s+[A-Za-z0-9+/=]+(?:\s+.*)?$/;
re.test(input);

Python

import re
bool(re.search(r"^ssh-(?:rsa|ed25519)\s+[A-Za-z0-9+/=]+(?:\s+.*)?$", text))

PHP

$ok = preg_match('/^ssh-(?:rsa|ed25519)\s+[A-Za-z0-9+\/=]+(?:\s+.*)?$/', $value) === 1;

Java

Pattern pattern = Pattern.compile("^ssh-(?:rsa|ed25519)\\s+[A-Za-z0-9+/=]+(?:\\s+.*)?$");
pattern.matcher(value).find();

Go

re := regexp.MustCompile(`^ssh-(?:rsa|ed25519)\s+[A-Za-z0-9+/=]+(?:\s+.*)?$`)
ok := re.MatchString(value)

Notes and production use

SSH Public Key regex is useful as a practical starting point. Test it against your real input, avoid using it as the only security control, and prefer a parser when the format has complex grammar.

Performance tip: avoid running complex regular expressions repeatedly on very large untrusted strings without limits. Prefer anchored validation patterns, cap input length before matching, and use a parser when the target format has nested grammar.