2

Can someone help me with a regular expression to get the year and month from a text string?

Here is an example text string:

http://www.domain.com/files/images/2012/02/filename.jpg

I'd like the regex to return 2012/02.

ruakh
  • 175,680
  • 26
  • 273
  • 307
jens
  • 75
  • 6
  • What software are you using? What have you tried? What don't you understand? – alexis Mar 18 '12 at 14:00
  • don't know much about regex. Tried to read up on it but seemed very complicated to me. Was hoping someone here would help me out. – jens Mar 18 '12 at 14:01
  • Alexis, I don't understand how regular expressions work. Looks like nonsense to me. I'm using php if that matters. – jens Mar 18 '12 at 14:04
  • @jens - **Well worth the effort of learning them.** Super super useful tool. They **are** however slightly complicated to grasp at first. But like I said - it will pay off. – Lix Mar 18 '12 at 18:33

2 Answers2

2

This regex pattern would match what you need:

(?<=\/)\d{4}\/\d{2}(?=\/)
Saeb Amini
  • 23,054
  • 9
  • 78
  • 76
1

Depending on your situation and how much your strings vary - you might be able to dodge a bullet by simply using PHP's handy explode() function.

A simple demonstration - Dim the lights please...

$str = 'http://www.domain.com/files/images/2012/02/filename.jpg';
print_r( explode("/",$str) );

Returns :

Array
(
    [0] => http:
    [1] =>
    [2] => www.domain.com
    [3] => files
    [4] => images
    [5] => 2012      // Jack
    [6] => 02        // Pot!
    [7] => filename.jpg
)

The explode() function (docs here), splits a string according to a "delimiter" that you provide it. In this example I have use the / (slash) character.

So you see - you can just grab the values at 5th and 6th index to get the date values.

Lix
  • 47,311
  • 12
  • 103
  • 131
  • ahh, didn't think of that. I do like the regex solution better though. – jens Mar 18 '12 at 19:17
  • Me too :) Its pretty :) But this is an alternative - come back to this once you have [pulled all your hair out](http://stackoverflow.com/a/1732454/558021) over regular expressions ;) **JOKES** – Lix Mar 18 '12 at 19:20