tags:

views:

107

answers:

5

I am learning regular expressions and I am trying find this string day1otlk_XXXX.gif where the 4 X's will be 3 to 4 random digits. This is what I have so far am I close?

qr/day1otlk_\d++\.gif/i
+1  A: 

Kinda close. You have the \d for digits.

Do you know what the range operator for regular expressions is?

Axeman
+1  A: 

Very close. This should do it...

day1otlk_\d{3,4}\.gif

The braces {} allow you to specify a ranged number of repeated characters {3,4} or an exact number like {4}.

Steve Wortham
+1  A: 

the regex should be /day1otlk_(\d{3,4})\.gif/, maybe /i for case-insensitivity. if it's in a string you might want /\bday1otlk_(\d{4})\.gif\b/ instead for stuff like "asdjklfhlday1otlk_5242.gifiasdytoi", which you probably don't want.

the {3,4} means that there need to be between three and four digits, and the parentheses to capture those four digits in \1 or $1.

(bonus un-asked-for answer: if you need exactly three or, say, five, you can't do that. {3,5} will get between three and five. you'd need \d{3}\d{2}? or something of the sort.)

sreservoir
For the bonus: `(\d{3}|\d{5})`.
Svante
that works too, yes. probably works better in pathological cases, too.
sreservoir
@Svante: Even better would be to optimize out the common part: `\d{3}(\d{2})?`
Ether
+1  A: 

You specify a range quantifier with curly braces:

qr/day1otlk_\d{3,4}\.gif/i
Eric Strom
+1  A: 

You can specify that there will be 3 or 4 digits with the following:

day1otlk_\d{3,4}\.gif

The {} is a repetition modifier. It's a little more precise than * or +. You can use it to specify an exact number of repetitions of the preceding pattern or a range of repetitions.

a{m} - exactly m a’s
a{m,} - at least m a’s
a{m,n} - at least m but at most n a’s

Bill the Lizard