2

I've the following string

Month: March 2011
Month: January 2012
Month: December 2011

and I'd like to write a regex which select the name of the month (ie "March") only for 2011. This mean to select everything between the string "Month: " and the year "2011". The regex I made is

^(Month:)[A-Za-z0-9]+(2011)$

but it doesn't seem to work. What's wrong??? The results should be "March" and "December". Thanks!

3 Answers 3

2

Use a lookahead:

/[a-z]+(?= 2011)/ig

See it here in action: http://regex101.com/r/fE9lR9

Here's a JavaScript demo: http://jsfiddle.net/rZJur/

Sign up to request clarification or add additional context in comments.

2 Comments

it works good but it is a little bit hard for me (a real newbie for regex) to understand how it work. It takes everything behind " 2011" but how it excludes the "Month: "?
@Nicolaesse [a-z] only matches characters, so the space between the colon and the month name acts as the barrier.
1

This expression works (look behind / look ahead) (?<=Month\:\s)(.+?)(?=\s2011).

Edit: With just Non-Capturing groups, this works: (?:Month\:\s)(.+?)(?:\s2011)

Comments

1

It isn't matching because you're not accounting for the white space in between the month and the year.

You could capture the month group after accounting for the space:

^(?:Month: )([A-Za-z]+)(?: 2011)$

Or you could use a look ahead/lookbehind combo:

(?<=^Month: )[A-Za-z]+(?= 2011$)

2 Comments

sorry mate but neither the first nor the second regex works for me, have a try at the following regex101.com/r/jV2qU8
You're right, the second one didn't work, I fixed it. But the first one does work, you just need to pull the result from that grouping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.