Dipit Sethi Dipit Sethi - 2 months ago 7
Perl Question

Need a regex for the following expression?

#! /usr/bin/perl

$str = "ab_cde,efg_gh,drg_fgt,main_xx,sum(abc),avg(def)";


or

$str = "ab_cde,bc_bn,gy_ihf,efg_gh,drg_fgt,main_xx,sum(abc),avg(def‌​)";


Guys, the string before
main_xx
is dynamic means there can be more elements with this format like
xx_xx
or
xxx_xx
or
xx_xxx
or
xxx_xxxx
or it can be as many characters before and after "underscore". So before
main_xx
, as many elements can come with above format. I want to match string UP TO main_xx
because even fetching dynamically, this "main_xx" will be the last element and want to ignore elements after
main_xx`. Please help to create a regex for this.

Answer
#!/usr/bin/perl -w
use strict;

my $str = "ab_cde,efg_gh,drg_fgt,main_xx,sum(abc),avg(def)";
(my $result) = ($str =~ m/(.*main_xx)/);
print $result;

The output will be everything up to main_xx (given xx is just the string made of x's).