How can I make $ 1 alternatives without replacing regex?

In a project, I recently joined abstract logic in code and database elements. Business logic, such as xPaths, regular expressions and function names, is entered into the database, and general code, such as reading files, creating xml from xpaths, etc., is in the code base.

Most (if not all) methods that use regular expressions are structured this way:

if ( $entry =~ /$regex/ ) { $req_value = $1; }

This means that only $ 1 is available, and you always need to write your regular expression to give you the desired result in $ 1.

Problem:

The result for the following lines should be either

'2.6.9-78.1.6.ELsmp (SMP)' or '2.6.9-78.1.6.ELsmp'

depending on the existence of SMP. $ 1 is not enough for $ entry [0].

$entry[0] = qq|Linux version 2.6.9-78.1.6.ELsmp (brewbuilder@hs20-bc2-2.build.redhat.com) (gcc version 3.4.6 20060404 (Red Hat 3.4.6-10)) #1 SMP Wed Sep 24 05:41:12 EDT 2008|;
$entry[1] = qq|Linux version 2.6.9-78.0.5.ELsmp (brewbuilder@hs20-bc2-2.build.redhat.com) (gcc version 3.4.6 20060404 (Red Hat 3.4.6-10)) #1 Wed Sep 24 05:41:12 EDT 2008|;

Hence my solution:

my $mutable = '';
my $regex = qr/((\d.*?)\s+(?:.*)?(SMP)((?{$mutable="$2 ($3)"}))|(\d.*?))\s+/;
if ($entry[$i] =~ /$regex/) {
    $req_value = $1; 
    $req_value = $mutable if ($mutable ne '');
    $mutable = '';
}

Unfortunately, the existence of a “variable” in the database makes this solution unacceptable.

:

  • , ?

  • regex 'if ($ entry = ~/$regex/)'?

.

+3
3

, , , - . , ,

if (my @fields = $_ =~ /$pat/) {
  $req_value = join " " => grep defined($_), @fields;
}

, , .. $1, $2, $3 .. .

qr/(\d+(?:[-.]\w+)*)(?:.*(SMP))?/

2.6.9-78.1.6.ELsmp SMP 2.6.9-78.0.5.ELsmp $req_value. grep defined($_) . undefined , SMP.

, , , $req_value. , , -

qr/(XYZ) OS (version \d+|v-\d+)/

, XYZ $req_value, . ,

qr/(XYZ) OS (?:version \d+|v-\d+)/

(?:...) ( $2 ): .

+2

. , ? , , . , 2 , .

Perl ? , :

if ( $entry =~ /$regex/ ) { $req_value = '$1 $2'; }

$regex = qr/((\d.*?)\s+(?:.*)?(SMP)/;?

- perl, .

, . , , PATTERN REPLACEMENT s/PATTERN/REPLACEMENT/ qr//. , . qr// , qr PATTERN . , s/// perl-, s///. , Perl-, .

: ? , , SMP , ?

0

5.10.0, (?|pattern) , . , 5.8, , , , Perl.

0

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


All Articles