[thelist] Regular expression for three or more consecutive occurrences of the same character

Chris Spruck cspruck at mindspring.com
Fri Feb 8 12:58:01 CST 2002


At 01:22 PM 2/8/02 -0500, Ben Gustafson wrote:
>  I'm wondering if there's a regular expression for this, one that could
> be changed to check for n number
>of the same character in a row. How 'bout it, regexp wizards out there?

Ben,

There are many different approaches to regex and these are a little
different than what Howard contributed. Some basic regexs would be
something like these:

q{3} - matches "q" exactly 3 times
q{3,} - matches "q" at least 3 times
q{3,5} - matches "q" at least 3 times and no more than 5 times

Those would find just q with those parameters, of course, knowing what q
would be ahead of time. Where you need to be careful would be a case where
you have something like :

[a-z]{3}

This won't find 3 q's, but ANY 3 characters, since the match that you're
looking for 3 times in that expression is any character from a to z and not
specific to q.

Howard Cheng wrote:

>The pattern you're looking for would be:
>
>/(\S)\1\1/

Another great solution for this problem, Howard! It's definitely the better
approach when you don't know what the character or match will be.

The \1 is what's called a backreference - basically a flag that recalls the
first match, which you can place back into the results, move around, act
upon, etc. The only caveat about using backreferences is that all
applications or languages might not necessarily support their use. I recall
some time ago finding an app (think it was an old version of Dreamweaver,
but that could be wrong) that didn't recognize backreferences at all. I
haven't had a chance to go back and confirm regex support for different
apps, JavaScript in different browsers, and so forth, but will be doing so
soon.

HTH!

Chris




More information about the thelist mailing list