Use lookbehind to count back as many chars as you want, and at the front of it, put a lookahead to check your pattern:
/.. # match first two chars
(?:(.) # capture next char, then
(?<= # looking behind,
(?!\1\1\1) # don't allow a run of three
...) # starting three chars back
){1,4}/x
This technique can also overcome some other variable-length lookbehind situations. For example, if you want to match "bar" that is preceded by "foo" somewhere in the preceding six characters:
/(?<= # looking behind,
(?=.{0,3}foo) # look for a foo preceded by up to three chars
.{6}) # starting six chars back
bar/x # then match bar
The thing to remember is that the lookahead
can see farther than the end of the lookbehind, so you need to explicitly limit it. You could use that feature to get a slightly different solution to the first problem:
/.. # match first two chars
(?:
(?<= # looking behind,
(?!(.)\1\1) # don't allow a run of three
..) # starting only two chars back
. # then match the next char
){1,4}/x
-
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.