Hi,
Disclaimer: I am not a regex wizzard, so I'm not sure if the following has any pitfalls, but it does appear to be possible with a single regex:
print $_, /(x(.*)x(??{ '.{'.length($2).'}' })x)/
? " matches, \$1 = $1\n" : " doesn't match\n"
for qw/ xxx x.x.x x12x..x x123x...x x1x2x...x
x123x.x.x x12x1x ax1x2xbx34x56xc /;
__END__
xxx matches, $1 = xxx
x.x.x matches, $1 = x.x.x
x12x..x matches, $1 = x12x..x
x123x...x matches, $1 = x123x...x
x1x2x...x matches, $1 = x1x2x...x
x123x.x.x matches, $1 = x123x.x.x
x12x1x doesn't match
ax1x2xbx34x56xc matches, $1 = x1x2xbx34x56x
Update: Changing the first part of the regex to x(.*?)x (non-greedy) will allow you to match all the substrings in that last example above (and the rest of the examples above will continue to work the same):
my $re = qr/(x(.*?)x(??{ '.{'.length($2).'}' })x)/;
my $str = "ax1x2xbx34x56xc";
while ($str=~/$re/g) {
print "found \"$1\"\n";
}
__END__
found "x1x2x"
found "x34x56x"
Hope this helps,
-- Hauke D
-
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.