2

I need a ruby regexp pattern that matches a string containing a letter (for simplicity say 'a') n times and then n at the end.

For example, it should match "aaa3", "aaaa4" etc but not "a2" or "aaa1", etc.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
n00b
  • 721
  • 1
  • 7
  • 18

3 Answers3

4

I can do it in Perl, but not in Ruby.

/^(a+)(??{length($1)})$/

Fun, eh?

Check it out: http://ideone.com/ShB6C

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
3

That is not possible in regex since it is not a regular language (that's easy to prove with the Pumping Lemma for Regular Languages). I'm not sure how much more powerful ruby regex is than a true Regular Expression, but I doubt it's powerful enough for this. You can set a finite limit on it and state each possibility like:

a1|aa2|aaa3|aaaa4|aaaaa5||aaaaaa6||aaaaaaa7||aaaaaaaa8||aaaaaaaaa9

Since all finite lanugages are regular, but it would be much easy to use string operations to count the number of times a letter appears and then parse for that integer in the string right after the last of that letter.

Paul
  • 139,544
  • 27
  • 275
  • 264
1

I just woke up, so take this with a grain of salt, but instead of doing it with a single regex, an easy way to do it would be

def f(s)
  s =~ /(a+)(\d)/
  $1.size == $2.to_i
end #=> nil
f 'aaa3' #=> true
f 'aa3' #=> false
Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
  • @all: I know to do in multi lines, I was just thinking whether it is possible in the same single regexp. – n00b Aug 24 '11 at 04:48