Save multiple regex buffers in variables in Ruby?

In Perl, I can do below and get the expected result admin1secretpw.

How do I do the same in Ruby? That is, save multiple buffers in variables.

#!/usr/bin/perl

my $a = 'admin1:secretpw@example.com';

(my $u = $1, my $p = $2) if $a =~ /(.*?):(.*?)@/;

print $u;
print $p;
+4
source share
3 answers

You can use named capture groups.

a = 'admin1:secretpw@example.com'     
/(?<username>.*?):(?<password>.*?)@/ =~ a

puts username
puts password

This captures both groups as local variables.

The question of arguments =~matters. Using ... =~ aassigns named groups to local variables, using a =~ ...will not.

+3
source

Please look at the end of the important Perl code note. With Ruby you can do

u, v = a.match(/(.*?):(.*?)@/)[1,2]

String # match. recongizes /.../ , Regexp, Regexp match . MatchData, . 0 , 1,2....

, nil, , if u.nil? NilClass.

if matched = a.match(/(.*?):(.*?)@/)
    u, v = matched.captures
end

MatchData # capture. $1 $2 .

, , , .

Ruby.

u, v = (/(.*?):(.*?)@/).match(a)[1,2]

/.../ Regexp, match .

, String # split

u, v = a.split(/:|@/)[0..1]

a :, @ .


Perl , .

, . my $x = 1 - , - . , , .

, ... ?

Statement perlsyn ( )

.. my, state our, (, my $x if ...), undefined. my undef, , , - . . perl - perl, . .

, Perl. , regex

my ($u, $p) = $a =~ /(.*?):(.*?)@/;

$u $p. , .

+3

Perl, , Ruby.

a = 'admin1:secretpw@example.com'

a =~ /(.*?):(.*?)@/
($1 && $2) ? (u, v = $1, $2) : nil
  #=> ["admin1", "secretpw"] 
u #=> "admin1" 
v #=> "secretpw" 

a = 'admin1?secretpw@example.com'

a =~ /(.*?):(.*?)@/
($1 && $2) ? (u, v = $1, $2) : nil
  #=> nil

a, uand pare local variables. @a, @uAnd @pare instance variables and $a, $uand $pwill be global variables.

The defendant obviously knows what the regex does, so I don't need to say anything about it.

Here are a few other ways to do this in Ruby.

a = 'admin1:secretpw@example.com'

rv = a.scan(/.+(?=:)|(?<=:).+?(?=@)/).flatten
  #=> ["admin1", "secretpw"]
rv.size == 2 ? (u, v = rv) : nil
  #=> ["admin1", "secretpw"] 
u #=> "admin1" 
v #=> "secretpw" 

and

rv = a.split(/[:\@]/).take(2)
  #=> ["admin1", "secretpw"] 
rv.size == 2 ? (u, v = rv) : nil
  #=> ["admin1", "secretpw"] 

See String # split .

0
source

Source: https://habr.com/ru/post/1664728/


All Articles