Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for only 2 letters

Tags:

regex

ruby

I need to create regular expression for 2 and only 2 letters. I understood it has to be the following /[a-z]{2}/i, but it matches any string with 2 or more letters. Here is what I get:

my_reg_exp = /[a-z]{2}/i
my_reg_exp.match('aa')    # => #<MatchData "aa">
my_reg_exp.match('AA')    # => #<MatchData "AA">
my_reg_exp.match('a')     # => nil
my_reg_exp.match('aaa')   # => #<MatchData "aa">

Any suggestion?

like image 548
Andrea Avatar asked Mar 23 '14 04:03

Andrea


3 Answers

You can add the anchors like this:

my_reg_exp = /^[a-z]{2}$/i

Test:

my_reg_exp.match('aaa')
#=> nil
my_reg_exp.match('aa')
#=> #<MatchData "aa">
like image 122
Yu Hao Avatar answered Oct 17 '22 20:10

Yu Hao


Hao's solution matches isn't locale sensitive. If this is important for your use case:

/\a[[:alpha:]]{2}\z/

2.0.0-p451 :005 > 'aba' =~ /\A[[:alpha:]]{2}\Z/
 => nil 
2.0.0-p451 :006 > 'ab' =~ /\A[[:alpha:]]{2}\Z/
 => 0 
2.0.0-p451 :007 > 'xy' =~ /\A[[:alpha:]]{2}\Z/
 => 0 
2.0.0-p451 :008 > 'zxy' =~ /\A[[:alpha:]]{2}\Z/
 => nil 

Per usual, if you need further assistance, leave a comment.

like image 21
hd1 Avatar answered Oct 17 '22 21:10

hd1


You can use /\b[a-z]{2}\b/i to match a two-letter string. /b Matches a word-break.

This means you can scan a string to find all occurrences:

'Foo is a bar'.scan(/\b[a-z]{2}\b/i) #=> ["is"]

Or find the first match in a string using:

'a bc def'[/\b[a-z]{2}\b/i] # => "bc"
like image 1
the Tin Man Avatar answered Oct 17 '22 21:10

the Tin Man