Very simple regex question

G

Geometric Patterns

Hi, I have a very simple regex question.

I don't understand why the regex in the example below isn't identifying
that the string is longer than 12 characters long...
line = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
if line =~ /[a-zA-Z]{2,12}/
puts "good"
else ?> puts "bad"
end
good
=> nil
Any ideas?

Many thanks in advance!
 
J

Jeremy Bopp

Hi, I have a very simple regex question.

I don't understand why the regex in the example below isn't identifying
that the string is longer than 12 characters long...
line = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
if line =~ /[a-zA-Z]{2,12}/
puts "good"
else ?> puts "bad"
end
good
=> nil
Any ideas?

Your regexp will match anywhere within the string where there is a run
of 2 to 12 characters. If you want to ensure that there is nothing
before or after whatever is matched, you need to use the begin and end
of string anchors as follows when you define your regexp:

/\A[a-zA-Z]{2,12}\z/

-Jeremy
 
H

Hassan Schroeder

I don't understand why the regex in the example below isn't identifying
that the string is longer than 12 characters long...
if line =~ /[a-zA-Z]{2,12}/

That succeeds if the string *contains* between 2 and 12 characters,
not if it consists solely of 2-12 characters.

line = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
if line =~ /[a-zA-Z]{2,12}/
puts "good" # you'll get this
else
puts "bad"
end

if line =~ /\A[a-zA-Z]{2,12}\Z/
puts "good"
else
puts "bad" # you'll get this
end

FWIW,
 

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,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top