Ruby Sub Regular Expression

D

Dave Roberts

Hello! I have a string: "Hello - 1 - World"

irb(main):017:0> a = "Hello - 1 - World"
=> "Hello - 1 - World"

I want to chop off the "Hello - " part. Hello could be any word, so I
want to match it generically.
To match the first minus I do this:

irb(main):018:0> b = a.sub(/\s-\s/, "")
=> "Hello1 - World"

Good! Now to get rid of the first word I try this:

irb(main):019:0> c = a.sub(/.*\s-\s/, "")
=> "World"

Bad! It matched to the second minus! Why does sub do this? I thought
it was supposed to match the first occurrence only.
 
J

Jim McKerchar

Hi. You missed out your non-greedy operator (if thats the right term) in
your regex.

Try:

a = "Hello - 1 - World"

c = a.sub(/.*?\s-\s/, "")

irb(main):004:0> c = a.sub(/.*?\s-\s/, "")
=> "1 - World"


Hope that helps
Jim
 
J

Jesús Gabriel y Galán

Hello! I have a string: "Hello - 1 - World"

irb(main):017:0> a = "Hello - 1 - World"
=> "Hello - 1 - World"

I want to chop off the "Hello - " part. Hello could be any word, so I
want to match it generically.
To match the first minus I do this:

irb(main):018:0> b = a.sub(/\s-\s/, "")
=> "Hello1 - World"

Good! Now to get rid of the first word I try this:

irb(main):019:0> c = a.sub(/.*\s-\s/, "")
=> "World"

Bad! It matched to the second minus! Why does sub do this? I thought
it was supposed to match the first occurrence only.

Because * by default is greedy, so it tries to match as much as it can.
Try this:

irb(main):002:0> c = a.sub(/.*?\s-\s/, "")
=> "1 - World"

Jesus.
 
R

Robert Klemme

Because * by default is greedy, so it tries to match as much as it can.
Try this:

irb(main):002:0> c = a.sub(/.*?\s-\s/, "")
=> "1 - World"

Other variants would be

irb(main):001:0> a = "Hello - 1 - World"
=> "Hello - 1 - World"
irb(main):002:0> a[/\d+\s+-.*/]
=> "1 - World"
irb(main):003:0> a.sub /^\S+\s+-\s+/, ''
=> "1 - World"
irb(main):004:0> a.sub /^\w+\s+-\s+/, ''
=> "1 - World"
irb(main):005:0>

Cheers

robert
 
J

Jim McKerchar

Thanks Henrik

Henrik said:
"lazy"

------------------------------------------------------------------------


Internal Virus Database is out of date.
Checked by AVG - http://www.avg.com
Version: 8.0.175 / Virus Database: 270.9.0/1777 - Release Date: 09/11/2008 09:53
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top