G'day Wcool,

You get the output:

MATCH = [](EntityName$ = DERIVED_ATTRIBUTE_TABLE, FieldNames$[]

because

  1. Regex '\[' matches character in line: '['.
  2. Regex '.+?' matches at least one character (']') and then continues to match non-greedily (i.e. up to but not including the next ']'), that's '(EntityName$ = DERIVED_ATTRIBUTE_TABLE, FieldNames$['.
  3. Regex '\]' matches the ']' after that.

So, instead of matching any character one or more times non-greedily (i.e. '.+?'), what you really want is to match any character that isn't ']' one or more times greedily (i.e. '[^\]]+').

You get the ouput:

MATCH = {} = { this is a test }

for much the same reasons. The fix is similar, changing '.+?' to '[^}]+'.

Also, unless you really want those extra captures, you can lose the two inner pairs of parentheses.

Here's my test:

#!/usr/bin/env perl -l use strict; use warnings; my $line = 'EntityMappingFetchByName?[](EntityName$ = DERIVED_ATTRIBUT +E_TABLE, FieldNames$[] = [ USER_ENTITY_NAME ], text${} = { this is a +test }), line 6'; my $re = qr< ( { [^}]+ } | \[ [^\]]+ \] ) >x; print "MATCH = $1" while $line =~ /$re/g;

Output:

MATCH = [ USER_ENTITY_NAME ] MATCH = { this is a test }

-- Ken


In reply to Re: Regular expressions: Extracting certain text from a line by kcott
in thread Regular expressions: Extracting certain text from a line by Wcool

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.