in reply to Regex for matching URLs with username/password and token

What about named capture groups?
#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; for my $string ( '--server api.blr-ocp1.lab.rbbn.com --username mgore --password ab +c123', '--server api.blr-ocp1.lab.rbbn.com --token kfjshdssahdvkbvjkbj' ) { if ($string =~ /^--server\s+(?<server>\S+)\s+ (?:--username\s+(?<username>\S+)\s+--password\s+(?<passwor +d>\S+) |--token\s+(?<token>\S+))/x ) { say 'Server: ', ${^CAPTURE}{server}; if (exists ${^CAPTURE}{token}) { say 'Token: ', ${^CAPTURE}{token}; } else { say 'Username: ', ${^CAPTURE}{username}; say 'Password: ', ${^CAPTURE}{password}; } } else { say 'No match'; } }

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Regex for matching URLs with username/password and token
by jdporter (Paladin) on Mar 10, 2025 at 20:22 UTC
    use Getopt::Long; for ( '--server api.blr-ocp1.lab.rbbn.com --username mgore --password ab +c123', '--server api.blr-ocp1.lab.rbbn.com --token kfjshdssahdvkbvjkbj', ) { local @ARGV = split; my( $server, $username, $password, $token ); GetOptions( 'server=s' => \$server, 'username=s' => \$username, 'password=s' => \$password, 'token=s' => \$token, ) or die; $server or die "--server is required\n"; $token && ($username || $password) and die "cannot provide --usern +ame or --password with --token\n"; ($username xor $password) and die "--username and --password must +be provided together\n"; $token || $username or die "must provide either --token or --usern +ame plus --password.\n"; if ($token) { } else # username+password { } }