# Problems with Sting#sub and regular expressions

**URL:** <https://www.ruby-forum.com/t/problems-with-sting-sub-and-regular-expressions/81072>\
**Category:** Ruby\
**Created:** [January 3, 2007, 4:14pm UTC](https://www.ruby-forum.com/t/problems-with-sting-sub-and-regular-expressions/81072 "2007-01-03T16:14:44Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Trish\_Ball](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/edb3f5/32.png) [@Trish\_Ball](https://www.ruby-forum.com/u/Trish_Ball)\
**Post date:** [January 3, 2007, 4:14pm UTC](https://www.ruby-forum.com/t/problems-with-sting-sub-and-regular-expressions/81072/1 "2007-01-03T16:14:44Z")

</div>

I have been working on an expression using String#sub and am getting  
inaccurate results on the first time I run the expression, but not on  
the  
following times I run it. Is there something wrong with my regular  
expression?

The intent of my regular expression is to remove preceding spaces and  
apostrophes.

irb(main):001:0\> " ’ Helen".sub(/^([’\s]_)(._)/, “#{$2}”)  
=\> “”  
irb(main):002:0\> " ’ Helen".sub(/^([’\s]_)(._)/, “#{$2}”)  
=\> "Helen

---

<div class="post-metadata">

**Author:** ![Trish\_Ball](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/edb3f5/32.png) [@Trish\_Ball](https://www.ruby-forum.com/u/Trish_Ball)\
**Post date:** [January 3, 2007, 4:20pm UTC](https://www.ruby-forum.com/t/problems-with-sting-sub-and-regular-expressions/81072/2 "2007-01-03T16:20:46Z")

</div>

I did change my expression to read:

irb(main):001:0\> " ’ Helen".sub(/^([’\s]\*)/, “”)  
=\> “Helen”

and that works on the first try… but I was just wondering why the  
previous  
example does not work.

Thanks,  
Trish

---

<div class="post-metadata">

**Author:** ![Trish\_Ball](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/edb3f5/32.png) [@Trish\_Ball](https://www.ruby-forum.com/u/Trish_Ball)\
**Post date:** [January 3, 2007, 4:46pm UTC](https://www.ruby-forum.com/t/problems-with-sting-sub-and-regular-expressions/81072/3 "2007-01-03T16:46:57Z")

</div>

Hi –

On Thu, 4 Jan 2007, Trish Ball wrote:

> > irb(main):001:0\> " ’ Helen".sub(/^([’\s]_)(._)/, “#{$2}”)  
> > =\> “”  
> > irb(main):002:0\> " ’ Helen".sub(/^([’\s]_)(._)/, “#{$2}”)  
> > =\> "Helen

What’s happening is that you’re sort of inter-leafing (-leaving?) the  
setting and using of $2. The $2 you use in the first replacement  
string is nil; in that context, it won’t pick up the match you just  
did.

Here’s a simpler example, for illustration:

irb(main):002:0\> “abc”.sub(/(a)/, “#$1”)  
=\> “bc”

# $1 was nil, so the ‘a’ got deleted. But _now_ $1 is ‘a’ (from the

# line that was just executed). Therefore…

irb(main):003:0\> “abc”.sub(/(a)/, “#$1”)  
=\> “abc”

# …this time, ‘a’ gets replaced with ‘a’.

David
