Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm looking to find the value of a string between to "key" characters. The key characters do not repeat.

For example with the "key" characters being "[" and "]" :

my $test = 'ajdjs34[abc123 ew]dia4 3ss ';

I want to find 'abc123 ew' using regex. The text within the "key" characters will vary in length as will the text outside of them.

Replies are listed 'Best First'.
Re: Using Regex to extract variable-length substring
by Laurent_R (Canon) on Oct 29, 2013 at 22:21 UTC

    You could use something like this:

    my $key = $1 if $test =~  /\[(.+?)]/;

      PERFECT! Tank ya berry much! I love the simplicity that regex can bring to solving a problem.

      StrangeDucks

      I REALLY need to learn regex

        I REALLY need to learn regex

        Just do it. ;-) I know that the task may look a bit daunting at first, and something like  /\[(.+?)]/ may look like cryptic noise for some one not knowing how to interpret those funny characters, but it is actually fairly easy to understand and learn the basics of regexes if given the proper explanations or the right tutorial. Granted, regexes can become fairly hairy, but for more common tasks, it is definitely worth the effort, especially when developing in Perl.