I would like to extract and construct some strings after identifying a substring that matches a pattern contain within square braquets:
e.g: if my text is ‘2 cups [9 oz] [10 g] flour ‘
i want to generate 4 strings out of this input:
- “2 cups” -> us
- “9 oz” -> uk imperial
- “10 g” -> metric
- “flour” -> ingredient name
As a beginning I have started to identify any square braquet that contains the oz keyword and wrote the following code but the match is not occurring. Any ideas and best practices to accomplish this?
p_oz = re.compile(r'\[(.+) oz\]', re.IGNORECASE) # to match uk metric
text = '2 cups [9 oz] flour'
m = p_oz.match(text)
if m:
found = m.group(1)
print found
You need to use
searchinstead ofmatch.re.matchtries to match the entire input string against the regex. That’s not what you want. You want to find a substring that matches your regex, and that’s whatre.searchis for.