tags:

views:

112

answers:

3

at night, after saying my prayers, i typically count sheep to help me fall asleep. i want a regular expression to help me with the correct count. i want the following strings to match

0
1sheep
2sheepsheep
3sheepsheepsheep

and so on.

what is the regular expression for this?

something like '(\d+)(sheep){\1}' if {\1} would do what i want it to do

what if i count my sheep in pairs (1sheepsheep and 2sheepsheepsheepsheep), what would the regular expression be then?

+3  A: 

Python's regular expression engine does not support parsing a matched subexpression to a repetition count, and I don't think this should be done with RegExp either.

The best bet is to combine RegExp matching and checking with code:

rx = re.compile(r'^(\d+)((?:sheep)*)$')
m = rx.match(theString)
if m and len(m.group(2)) == 5 * int(m.group(1)):
   print ("Matched")
KennyTM
+1  A: 

You can extract the digits using a regex, and then compile a second regex using that number on the repetition operator:

import re
theString = '2sheepsheep'

rx = re.compile(r'^(\d+)(sheep)*$')
m = rx.match(theString)

rx = re.compile(r'^(\d+)(sheep){' + m.group(1) + '}$')
# If you count in pairs, you can just change that to:
rx = re.compile(r'^(\d+)(sheepsheep){' + m.group(1) + '}$')
NullUserException
+2  A: 

This is not something you should do with regex alone; you should first match the number at the start of the string and then dynamically generate a regex to match the rest. See the other answers for code examples.

I believe this is doable using Perl regexes (search for (?PARNO)). This is probably why I don't like Perl.

katrielalex
+1 for the dig on perl.
aaronasterling
The question is on Python, not Perl.
KennyTM
@KennyTM. I know... I probably shouldn't have posted anything, but I couldn't miss a chance for a dig at Perl. I'll edit.
katrielalex