Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex to match pattern of two digit number before a string

I have a text as so:

text = "There is 18 years of experience in marketing, with 5 years in sales."

I want to create a regex rule that will extract \d\d + "years" so that it may extract any one and two digit number followed by the keyword ‘years’ or ‘Years’ or ‘Yrs’ from any corpus.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected output: ["18 year", "5 years"]

I tried

text = re.findall(r'\d\d +years', text)

which returned None

How to get this?

>Solution :

Try this pattern: \d{1,2} (?:yrs|years?) with flag IGNORECASE in python.

See Regex Demo

Explanation

  • \d{1,2}: capture one or two-digit.
  • (?:: is a non-captured group.
  • yrs|years: this captures "yrs" or "years". (case-insensitive)
  • ?: this after "y" means "s" can be or not.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading