Regular expression - first two alphabets of a string

Hi All,

I learning regular expressions in Ruby and I want to do the following
thing with a strings

“A sting should not start with two a i.e aa”

example

“aa xyz” - wrong
“axyz” - is fine
“a xyz” is fine

please help.

Regards,

def matchaa (str)

if str.match(/^aa/)
return true
else
return false
end
end

On 5/3/07, Ravi S. [email protected] wrote:

“axyz” - is fine
“a xyz” is fine

please help.

Regards,


Posted via http://www.ruby-forum.com/.


अभिजीत

[ written in http://www.paahijen.com/scratchpad ]

[ http://www.paahijen.com ]

Abhijit,

I tried the method for “aa xyz” and it return true actually it should
return false.

Regards,

On 03.05.2007 19:33, Abhijit G. wrote:

def matchaa (str)

if str.match(/^aa/)
return true
else
return false
end
end

This does not seem to be worth a method…

raise “Illegal String: #{str}” if /\Aaa/ =~ str

Kind regards

robert

On 5/3/07, Abhijit G. [email protected] wrote:

Hi All,
“a xyz” is fine

Or use a negative lookahead:
irb(main):001:0> re = /^(?!aa)/
=> /^(?!aa)/
irb(main):002:0> “aa xyz”.match(re)
=> nil
irb(main):003:0> “axyz”.match(re)
=> #MatchData:0xb7baf3e4
irb(main):004:0> “a yz”.match(re)
=> #MatchData:0xb7bacb1c


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

Thanks Rick -ve lookahead helped.

Regards,

sorry! I misread your post! :frowning:

On 5/3/07, Ravi S. [email protected] wrote:


अभिजीत

[ written in http://www.paahijen.com/scratchpad ]

[ http://www.paahijen.com ]

On 03.05.2007 20:30, Rick DeNatale wrote:

On 5/3/07, Ravi S. [email protected] wrote:

“axyz” - is fine
irb(main):004:0> “a yz”.match(re)
=> #MatchData:0xb7bacb1c

What exactly do you gain by using lookahead instead of a normal match?

Kind regards

robert

Robert K. wrote:

On 03.05.2007 20:30, Rick DeNatale wrote:

On 5/3/07, Ravi S. [email protected] wrote:

“axyz” - is fine
irb(main):004:0> “a yz”.match(re)
=> #MatchData:0xb7bacb1c

What exactly do you gain by using lookahead instead of a normal match?

Kind regards

robert

When Rick directed me to use -ve lookahead I reach the following page
and it made the point clear.

Regards,

On 5/4/07, Robert K. [email protected] wrote:

On 03.05.2007 20:30, Rick DeNatale wrote:

What exactly do you gain by using lookahead instead of a normal match?

The OP was asking for an RE which matched anything which DIDN’T start
with aa.

The proposal using if else got it backwards.

Of course you could also just negate the results of the match and use

!str.match(/aa/)

If you just wanted a test.


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

IPMS/USA Region 12 Coordinator
http://ipmsr12.denhaven2.com/

Visit the Project Mercury Wiki Site
http://www.mercuryspacecraft.com/