Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve Nested quantifiers in regex?

Tags:

regex

grep

perl

Getting stuck at

my $count=grep {/$str_check/} @arr_name ;

when

$str_check = 'C/C++'

It throws Nested quantifiers in regex; marked by <-- HERE in m/'C/C++ <-- HERE '/ at acr_def_abb_use.pl line 288

I tried by changing into

my $count=grep {/"$str_check"/} @arr_name ;

and

my $count=grep {/'$str_check'/} @arr_name ;

But both didn't work. Any one please help me out with this.

like image 294
Praveen kumar Avatar asked Feb 09 '26 18:02

Praveen kumar


2 Answers

You need to generate a regular expression pattern that matches the text. Specifically, you want C/C\+\+.

my $text  = 'C/C++';
my $pat   = quotemeta($text);
my $count = grep { /$pat/ } @arr_name;

or

my $text  = 'C/C++';
my $count = grep { /\Q$text\E/ } @arr_name;

(The \E can be omitted since it's at the end.)

like image 103
ikegami Avatar answered Feb 12 '26 16:02

ikegami


I can't reproduce your problem, but it is good practice to use quotemeta for special characters:

use warnings;
use strict;

my @arr_name = ('dgsdjhg','bar C/C++ foo', 'bbbb', 'C/C++');
my $str_check = quotemeta 'C/C++';
my $count = grep { /$str_check/ } @arr_name;
print "$count\n";
like image 20
toolic Avatar answered Feb 12 '26 16:02

toolic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!