n00b
n00b

Reputation: 731

Need a regular expression to match a dynamically-determined repeat count

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.

Upvotes: 2

Views: 494

Answers (3)

Michael Kohl
Michael Kohl

Reputation: 66867

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

Upvotes: 1

Ray Toal
Ray Toal

Reputation: 88478

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

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

Fun, eh?

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

Upvotes: 4

Paul
Paul

Reputation: 141927

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.

Upvotes: 3

Related Questions