# How to find out the number of pattern matched?

**URL:** <https://www.ruby-forum.com/t/how-to-find-out-the-number-of-pattern-matched/111208>\
**Category:** Ruby\
**Created:** [August 3, 2007, 8:47pm UTC](https://www.ruby-forum.com/t/how-to-find-out-the-number-of-pattern-matched/111208 "2007-08-03T20:47:23Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [August 3, 2007, 8:47pm UTC](https://www.ruby-forum.com/t/how-to-find-out-the-number-of-pattern-matched/111208/1 "2007-08-03T20:47:23Z")

</div>

Hi all,

I search a pattern in a string. How do I know how many times the pattern  
is found/matched?

Thanks,

Li

---

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [August 3, 2007, 9:03pm UTC](https://www.ruby-forum.com/t/how-to-find-out-the-number-of-pattern-matched/111208/2 "2007-08-03T21:03:54Z")

</div>

Li Chen wrote:

> I search a pattern in a string. How do I know how many times the pattern  
> is found/matched?

string.scan(pattern).length

HTH,  
Sebastian

---

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [August 3, 2007, 11:34pm UTC](https://www.ruby-forum.com/t/how-to-find-out-the-number-of-pattern-matched/111208/3 "2007-08-03T23:34:26Z")

</div>

Sebastian H. wrote:

> Li Chen wrote:
> 
> > I search a pattern in a string. How do I know how many times the pattern  
> > is found/matched?
> 
> string.scan(pattern).length
> 
> HTH,  
> Sebastian

Thanks,

Li
