Home > Software design >  Regex: match based on two exact words/sentence structure
Regex: match based on two exact words/sentence structure

Time:05-22

I am trying to extract the interest rate target range from the string below. I only need to extract "0 to 1/4 percent" where the exact numbers can change but the rate is always specified in the given format i.e., (number) to (number) percent. The numbers could be in either of the two formats digit or digit/digit.

strr = "The Committee will maintain the target range for the federal funds rate at 0 to 1/4 percent and continues to anticipate that economic conditions, including low rates of resource utilization, subdued inflation trends, and stable inflation expectations, are likely to warrant exceptionally low levels for the federal funds rate for an extended period."  

Have tried a couple of things but can't figure it out. Thanks!

CodePudding user response:

You can use:

import re

re.findall(r'(\d (?:/\d )?\s*to\s*\d (?:/\d )?\s*percent)', strr)

Output: ['0 to 1/4 percent']

How the regex works: regex demo

CodePudding user response:

You can try this:

lst = ["at 0 to 12 percent and", 
       "at 1/8 to 1/2 percent and", 
       "at 0 to 1/4 percent and", 
       "at 12 to 28 percent and", 
       "at 1/2 to 50 percent and"]

pattern=r"((\d{1,2}|\d/\d) to (\d{1,2}|\d\/\d)) percent"
for elem in lst:
    res = re.search(pattern, elem)[0]
    print(res)

0 to 12 percent
1/8 to 1/2 percent
0 to 1/4 percent
12 to 28 percent
1/2 to 50 percent
  • Related