Home > Software engineering >  How to create a regex for adding single line valid ssh-key
How to create a regex for adding single line valid ssh-key

Time:10-12

Currently in my application users are able to add multi-line ssh-keys in a field. Also user can paste as many ssh-keys as they want in that field. Right now I have the following regex for this behavior:

const publicSshKeyRegex = /^(ssh-rsa AAAAB3NzaC1yc2|ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNT|ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzOD|ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1Mj|ssh-ed25519 AAAAC3NzaC1lZDI1NTE5|ssh-dss AAAAB3NzaC1kc3)[0-9A-Za-z /] [=]{0,3}(\s.*)?(\n|$)/;

But now what I want is that not to allow users to add multi-line ssh-keys and not to allow them to add several ssh-keys. It means that user will be able to add only one ssh-key and it should be in a single line. So the expected behavior would be To add only one ssh-key, single line.

Could anyone help me to create a new regex for new expecting behavior?

CodePudding user response:

This part in the pattern (\s.*)? optionally matches a whitespace char (that can also match a newline) followed by the rest of the string, allowing for 2 lines to be matched.

If you want a single line only, you can omit that part, and add .* to match the rest of the line, followed by an optional newline and assert the end of the string.

Doing so, this is part [=]{0,3} becomes optional and the character class [0-9A-Za-z /] can be shortened to match at least a single character.

^(?:ssh-rsa AAAAB3NzaC1yc2|ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNT|ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzOD|ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1Mj|ssh-ed25519 AAAAC3NzaC1lZDI1NTE5|ssh-dss AAAAB3NzaC1kc3)[0-9A-Za-z /].*\n?$

Regex demo

const regex = /^(?:ssh-rsa AAAAB3NzaC1yc2|ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNT|ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzOD|ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1Mj|ssh-ed25519 AAAAC3NzaC1lZDI1NTE5|ssh-dss AAAAB3NzaC1kc3)[0-9A-Za-z /].*\n?$/;
[
  "ssh-rsa AAAAB3NzaC1yc2a",
  "ssh-rsa AAAAB3NzaC1yc2a\n",
  "ssh-rsa AAAAB3NzaC1yc2a\ntest\n"
].forEach(s => console.log(`${s} --> ${regex.test(s)}`));

  • Related