>perl -wMstrict -le
"for (@ARGV) {
if(/^A (?: Z | (\s.*?)) Z$/x) {
my $grabbed = $1 // '';
print qq{matched '$_' grabbed '$grabbed'};
}
}
" AZ AZZ AXZ "A SOMETHING Z" ASOMETHINGZ
matched 'AZZ' grabbed ''
matched 'A SOMETHING Z' grabbed ' SOMETHING '
I wonder why it is necessary to match something like 'AZZ' and yet grab an undefined value from it, which must later be rationalized Update: to an empty string. (Additionally, the regex Update: first regex
of the OP does not match 'AZ', which seems to be required by the OP.)
Wouldn't it make more sense only to grab stuff from strings that match? E.g., "if there is anything between A and Z, it must begin with a space and be followed by zero or more non-Z characters". (Has the advantage of matching 'AZ', no defined test needed.)
>perl -wMstrict -le
"for (@ARGV) {
if(/^A ((?: \s [^Z]*)?) Z$/x) {
print qq{matched '$_' grabbed '$1'};
}
}
" AZ AZZ AXZ "A ZZ" "A SOMETHING Z" ASOMETHINGZ "A Z" "A Z"
matched 'AZ' grabbed ''
matched 'A SOMETHING Z' grabbed ' SOMETHING '
matched 'A Z' grabbed ' '
matched 'A Z' grabbed ' '
Updates:
-
However, the 'Z' still needs to be repeated in the regex! Oh, well...
-
Added "A Z" and "A Z" test cases to my solution.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|