# Regex failure notifcation

**URL:** <https://www.ruby-forum.com/t/regex-failure-notifcation/126146>\
**Category:** Ruby\
**Created:** [January 15, 2008, 8:31pm UTC](https://www.ruby-forum.com/t/regex-failure-notifcation/126146 "2008-01-15T20:31:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Junkone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e274bd/32.png) [@Junkone](https://www.ruby-forum.com/u/Junkone)\
**Post date:** [January 15, 2008, 8:31pm UTC](https://www.ruby-forum.com/t/regex-failure-notifcation/126146/1 "2008-01-15T20:31:14Z")

</div>

When i match a pattern and if it returns a nil, obviously the regex  
did not match the pattern. is there a way of identifying which set did  
not match  
pattern=Regexp.new(’([g|l])\s+([0-9.]+)’)  
irb(main):073:0\> pattern.match(‘g 32’)  
=\> #MatchData:0x2e158b4  
irb(main):074:0\> pattern.match(‘g we’)  
=\> nil  
irb(main):075:0\>

If i can detect that the $2 failed and $1 was ok, i can pass more  
intelligent error messages.

---

<div class="post-metadata">

**Author:** ![Junkone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e274bd/32.png) [@Junkone](https://www.ruby-forum.com/u/Junkone)\
**Post date:** [January 16, 2008, 5:26am UTC](https://www.ruby-forum.com/t/regex-failure-notifcation/126146/2 "2008-01-16T05:26:27Z")

</div>

> If i can detect that the $2 failed and $1 was ok, i can pass more  
> intelligent error messages.

You could change the regular expression to  
pattern=Regexp.new(’([g|l])?\s+([0-9.]+)?’)  
m = pattern.match(‘g 32’)  
m[1] = ‘g’  
m[2] = ‘32’  
m = pattern.match(‘g we’)  
m[1] = ‘g’  
m[2] = nil # \<- Check for nil here to know that only the first part  
matched.  
m = pattern.match(‘a 32’)  
m[1] = nil # \<- First part failed  
m[2] = ‘32’  
m = pattern.match(‘32 g’)  
m = nil # \<- The whole pattern failed

You’ll have to check that this new regular expression correctly matches  
your  
use case though.

Andrew T.  
removed\_email\_address@domain.invalid  
082 415 8283  
skype: andrewtimberlake

“I have never let my schooling interfere with my education.”  
–Mark Twain
