# How to search words starting with a particular char?

**URL:** <https://www.ruby-forum.com/t/how-to-search-words-starting-with-a-particular-char/136498>\
**Category:** Ruby\
**Created:** [May 2, 2008, 7:30pm UTC](https://www.ruby-forum.com/t/how-to-search-words-starting-with-a-particular-char/136498 "2008-05-02T19:30:56Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![toki](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/87869e/32.png) [@toki](https://www.ruby-forum.com/u/toki)\
**Post date:** [May 2, 2008, 7:30pm UTC](https://www.ruby-forum.com/t/how-to-search-words-starting-with-a-particular-char/136498/1 "2008-05-02T19:30:56Z")

</div>

Hi to all!

I need to search how many words are starting with a specific character  
in a text file, no problem to read the file, but after that I split it  
in words, how can  
I search all occurencies that’s matching my criteria in the resulting  
array? Maybe split isn’t the best solution?

I would like an output similar to this:

Number of words starting with ’ ’ = 12345

Here’s the code:

txt = File.read(“C:\text.txt”)

list = txt.split

Thanks.

Best regards.

---

<div class="post-metadata">

**Author:** ![toki](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/87869e/32.png) [@toki](https://www.ruby-forum.com/u/toki)\
**Post date:** [May 2, 2008, 8:18pm UTC](https://www.ruby-forum.com/t/how-to-search-words-starting-with-a-particular-char/136498/2 "2008-05-02T20:18:47Z")

</div>

> I need to search how many words are starting with a specific character

A word border can be matched with \b.

Using split + grep:  
irb(main)\> a = ‘foo bar foo bar foo bar’  
irb(main)\> a.split(/\b/).grep(/^f\w\*/)  
=\> [“foo”, “foo”, “foo”]  
irb(main)\> a.split(/\b/).grep(/^f\w\*/).size  
=\> 3

Another solution would be to use scan:  
irb(main)\> a.scan(/\bf\w\*/)  
=\> [“foo”, “foo”, “foo”]  
irb(main)\> a.scan(/\bf\w\*/).size  
=\> 3

---

<div class="post-metadata">

**Author:** ![toki](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/87869e/32.png) [@toki](https://www.ruby-forum.com/u/toki)\
**Post date:** [May 2, 2008, 11:54pm UTC](https://www.ruby-forum.com/t/how-to-search-words-starting-with-a-particular-char/136498/3 "2008-05-02T23:54:06Z")

</div>

ThoML wrote:

> > I need to search how many words are starting with a specific character
> 
> A word border can be matched with \b.
> 
> Using split + grep:  
> irb(main)\> a = ‘foo bar foo bar foo bar’  
> irb(main)\> a.split(/\b/).grep(/^f\w\*/)  
> =\> [“foo”, “foo”, “foo”]  
> irb(main)\> a.split(/\b/).grep(/^f\w\*/).size  
> =\> 3
> 
> Another solution would be to use scan:  
> irb(main)\> a.scan(/\bf\w\*/)  
> =\> [“foo”, “foo”, “foo”]  
> irb(main)\> a.scan(/\bf\w\*/).size  
> =\> 3

Thanks a lot for the helpful and fast answer.

Best regards.
