# Regular expression: Is this a bug or feature?

**URL:** <https://www.ruby-forum.com/t/regular-expression-is-this-a-bug-or-feature/83044>\
**Category:** Ruby\
**Created:** [January 23, 2007, 9:21am UTC](https://www.ruby-forum.com/t/regular-expression-is-this-a-bug-or-feature/83044 "2007-01-23T09:21:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mkrauskopf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/c37758/32.png) [@mkrauskopf](https://www.ruby-forum.com/u/mkrauskopf)\
**Post date:** [January 23, 2007, 9:21am UTC](https://www.ruby-forum.com/t/regular-expression-is-this-a-bug-or-feature/83044/1 "2007-01-23T09:21:17Z")

</div>

Hi ruby experts!

Is this intended behaviour?

irb(main):001:0\> s1=‘a=1’  
=\> “a=1”  
irb(main):002:0\> s2=‘b=1’  
=\> “b=1”  
irb(main):003:0\> s1 =~ /a|b=(.)/  
=\> 0 \<------ expression matches  
irb(main):004:0\> $1  
=\> nil \<------ but where is argument?  
irb(main):005:0\> s2 =~ /a|b=(.)/  
=\> 0 \<------ expression matches  
irb(main):006:0\> $1  
=\> “1” \<------ this has been expected  
irb(main):007:0\> s1 =~ /(a|b)=(.)/  
=\> 0 \<------ expression matches  
irb(main):012:0\> $2  
=\> “1” \<------ this has been expected

Tested on ruby 1.8.2 (2004-12-22) [i686-linux]

Thanks for your help in advance  
Martin.

---

<div class="post-metadata">

**Author:** ![mkrauskopf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/c37758/32.png) [@mkrauskopf](https://www.ruby-forum.com/u/mkrauskopf)\
**Post date:** [January 23, 2007, 9:41am UTC](https://www.ruby-forum.com/t/regular-expression-is-this-a-bug-or-feature/83044/2 "2007-01-23T09:41:19Z")

</div>

> irb(main):001:0\> s1=‘a=1’  
> =\> “a=1”  
> irb(main):003:0\> s1 =~ /a|b=(.)/  
> =\> 0 \<------ expression matches  
> irb(main):004:0\> $1  
> =\> nil \<------ but where is argument?  
> You wanted to do s1 =~ /(?:a|b)=(.)/. The | operator has a low  
> precedence  
> in regexps

---

<div class="post-metadata">

**Author:** ![mkrauskopf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/c37758/32.png) [@mkrauskopf](https://www.ruby-forum.com/u/mkrauskopf)\
**Post date:** [September 25, 2007, 10:33pm UTC](https://www.ruby-forum.com/t/regular-expression-is-this-a-bug-or-feature/83044/3 "2007-09-25T22:33:40Z")

</div>

On Tue, Jan 23, 2007 at 05:43:53PM +0900, George O. wrote:

> I’m not sure why you think it might be a bug. The ‘|’ operator just  
> binds very loosely, so you have to group the “a|b” in parens. Note  
> that in part 1, The bit that matches is the left side of the ‘|’,  
> namely ‘a’ (no parens), so there are no captures. In part 2, the  
> right side (‘b=(.)’) matches, so there’s 1 capture. In part 3, it  
> matches the whole thing (’(a|b)=(.)’), so there are 2 captures.
> 
> Does this make sense?

I always assumed ‘a|b anything’ means ‘(a|b) anything’.

Thanks for this clarification!

Regards  
Martin
