2

I have a string from which I want to extract month name and year with Python regex. The string looks like the following-

x='januray valo na Feb 2017 valo Jan-2015 anj 1900 puch Janu Feb Jan Mar 15 MMMay-85 anF 15'

I code should return the following-

['Feb 2017', 'Jan-2015', 'Mar 15', 'May-85']

I have tried-

re.findall('[Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec]{3}[\s-]\d{2,4}', x)

But I the code picking up anF 15 as well, i.e. I am getting the following output-

['Feb 2017', 'Jan-2015', 'Mar 15', 'May-85', 'anF 15']

How can I stop the code from picking up wroong combinations like Jan|Feb?

3 Answers 3

4

Use an alternation for the abbreviated month names. That is, use the following regex pattern:

(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[\s-]\d{2,4}

This says what you intend, namely to match one of 12 abbreviated month names, followed by a space/dash, then 2 or 4 digits.

x = 'januray valo na Feb 2017 valo Jan-2015 anj 1900 puch Janu Feb Jan Mar 15 MMMay-85 anF 15'

results = re.findall('(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[\s-]\d{2,4}', x)
print(results)

['Feb 2017', 'Jan-2015', 'Mar 15', 'May-85']

The problem with your current pattern is that it using a character class:

[Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec]{3}[\s-]\d{2,4}

This actually says to match three letters from the letters contained by the month names (plus pipe). Put another way, you are saying this:

[abceglnoprtuvyADFJMNOS|]{3}[\s-]\d{2,4}
Sign up to request clarification or add additional context in comments.

Comments

1

You are using character class here [Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec]{3}, which means any character from the character collection with repetition 3({3}). In order to fix it use a non-capturing group instead.

re.findall('(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[\s-]\d{2,4}', x)

Comments

1

/[a-z]{3}.?\d{4}/gi

this will work check here

Comments

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.