Regular expression - first two alphabets of a string


#1

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,


#2

def matchaa (str)

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

On 5/3/07, Ravi S. removed_email_address@domain.invalid 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 ]


#3

Abhijit,

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

Regards,


#4

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


#5

On 5/3/07, Abhijit G. removed_email_address@domain.invalid 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/


#6

Thanks Rick -ve lookahead helped.

Regards,


#7

sorry! I misread your post! :frowning:

On 5/3/07, Ravi S. removed_email_address@domain.invalid wrote:


अभिजीत

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

[ http://www.paahijen.com ]


#8

On 03.05.2007 20:30, Rick DeNatale wrote:

On 5/3/07, Ravi S. removed_email_address@domain.invalid 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


#9

Robert K. wrote:

On 03.05.2007 20:30, Rick DeNatale wrote:

On 5/3/07, Ravi S. removed_email_address@domain.invalid 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.

http://www.regular-expressions.info/lookaround.html

Regards,


#10

On 5/4/07, Robert K. removed_email_address@domain.invalid 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/