A
A
Andrey Barbolin2016-01-13 17:26:49
Perl
Andrey Barbolin, 2016-01-13 17:26:49

Perl, how to extract from a string what is in square brackets []?

Good afternoon.
I've been fighting over the regular season for the second day, there are workarounds for solving the issue, but I want to do it beautifully.
There is a line:
vs-mm-net-ht01[3]: ESTABLISHED 32 minutes ago, 77.164.204.11[vs-mm-vps-ht01]...221.163.147.23[vs-mn-net-kt01]
It is necessary to define in one line 3 variables
Type like this, but doesn't work: ($num, $tunnel_from, $tunnel_to) = split(/\[(.*?)\]/, $_);
that is, so that the variables get the following values:
num=3
tunnel_from = vs-mm-vps-ht01
tunnel_to = vs-mn-net-kt01

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vaut, 2016-01-13
@dronmaxman

head-on

# Если в строке бывает ровно три квадратных скобки
/\[(.*)\].*\[(.*)\].*\[(.*)\]/; 
($num, $tunnel_from, $tunnel_to)=($1,$2,$3)

doesn't fit?
More graceful:
($num, $tunnel_from, $tunnel_to) = /\[(.+?)\]/g

A
Andrey Barbolin, 2016-01-13
@dronmaxman

Not the prettiest option. But it will do. Are there other options?
I also decided in 2 lines, but it's not so interesting)
@num=split(/[\[\]]/, $_);
($tunnel_to, $num, $tunnel_from) = (${num[0]}, ${num[1]}, ${num[3]});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question