# Regular Expression {m,n}

**URL:** <https://www.ruby-forum.com/t/regular-expression-m-n/158155>\
**Category:** Ruby\
**Created:** [January 19, 2009, 9:46pm UTC](https://www.ruby-forum.com/t/regular-expression-m-n/158155 "2009-01-19T21:46:30Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mmcolli00](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/85e7bf/32.png) [@mmcolli00](https://www.ruby-forum.com/u/mmcolli00)\
**Post date:** [January 19, 2009, 9:46pm UTC](https://www.ruby-forum.com/t/regular-expression-m-n/158155/1 "2009-01-19T21:46:30Z")

</div>

File.open(“patientrecords.txt”, ‘r’) do |p|  
if p.gets =~ /%{2,3}PersonID/ then  
puts “PersonID exist twice”  
end  
end

Hi.  
This is supposed to tell me if there a line in my text file that  
contains ‘PersonID’ at least 2 times and at most 3 times. I have been  
playing with regular expressions and thinking {m,n} would help with  
this. This snippet is used to show me if it will actually work. (Some  
lines contain PersonID only once, I do not want to use those lines)

Thanks, MC

---

<div class="post-metadata">

**Author:** ![mmcolli00](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/85e7bf/32.png) [@mmcolli00](https://www.ruby-forum.com/u/mmcolli00)\
**Post date:** [January 19, 2009, 10:55pm UTC](https://www.ruby-forum.com/t/regular-expression-m-n/158155/2 "2009-01-19T22:55:47Z")

</div>

On 19.01.2009 21:45, Mmcolli00 Mom wrote:

> File.open(“patientrecords.txt”, ‘r’) do |p|  
> if p.gets =~ /%{2,3}PersonID/ then  
> puts “PersonID exist twice”

That output would be wrong, even if your matching would work the way you  
want it to.

> end  
> end
> 
> This is supposed to tell me if there a line in my text file that  
> contains ‘PersonID’ at least 2 times and at most 3 times.

It won’t work. {m,n} needs to be placed _after_ the bit you want to  
repeat. Also, it will match only immediate repetition unless you take  
measures to avoid that.

Having said that using scan(/PersonID/).size is probably simpler…

> I have been  
> playing with regular expressions and thinking {m,n} would help with  
> this. This snippet is used to show me if it will actually work. (Some  
> lines contain PersonID only once, I do not want to use those lines)

I can’t seem to find a question in your posting…

Cheers

robert

---

<div class="post-metadata">

**Author:** ![mmcolli00](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/85e7bf/32.png) [@mmcolli00](https://www.ruby-forum.com/u/mmcolli00)\
**Post date:** [January 19, 2009, 11:04pm UTC](https://www.ruby-forum.com/t/regular-expression-m-n/158155/3 "2009-01-19T23:04:44Z")

</div>

Thanks for pointing me in the right direction. Its been a long day  
already --\> maybe that’s why I didn’t know that I didn’t put the  
question out there - Yikes. I apologize. Thanks for replying. MC
