Abhishek
Abhishek

Reputation: 81

how to pass one regex output to another regex in perl

How to combine two regex . This is my input:

1.UE_frequency_offset_flag  else { 2}   UE_frequency_offset_flag
2.served1   0x00    Uint8,unsigned char
#my first regex expression is used for extracting the values inside curly braces 
my ($first_match) = /(\b(\d+)\b)/g;
print "$1 \n";
#my second regex expression   
my ($second_match) = / \S \s+ ( \{ [^{}]+ \} | \S+ ) /x;

I was trying to combine both regex but did not get the expected output.

my ($second_match) = / \S \s+ ( \{ [^{}]+ \} |\b(\d+)\b| \S+ ) /x;

My expected output:

2,0x00

Please help where I am doing mistake?

Upvotes: 1

Views: 691

Answers (1)

b-brankovics
b-brankovics

Reputation: 93

The question is not completely clear to me, because I don't see how you want to combine two regex or pass the output of one to the other.

  • If you want to pass the captured part of the first regex then you need to save it to a variable:

    my ($first_match) = /(\b(\d+)\b)/g;
    my $captured = $1;
    

    Then you can place the variable $captured in the second regex.

  • If you want to use the complete match and search inside that. Then you need to do the following:

    my ($first_match) = /(\b(\d+)\b)/g;
    print "$1,"; # Don't print one space then new line if you want to have a comma separating the two values
    my ($second_match) = $first_match =~ / \S \s+ ( \{ [^{}]+ \} | \S+ ) /x;
    

Based on your input, this won't generate the expected output.

The following code would print out:

2,0x00

When processing your input.

print "$1," if /\{\s*(\d+)\s*\}/;
print "$1\n" if /(\d+x\d+)/;

Upvotes: 2

Related Questions