简体   繁体   中英

How to make a Python regex pattern match a certain character at the start, or just be the start of the string?

This is my code so far I've been working on in Python 2.7

import re

length_pattern = r"(?P<amount>[\d]{1,3}|(quarter)|(half)|(a[n]?))?[.]*(?P<type>(minute)|(hour)|(day)[s]?)?"

response='half hour '

length = re.search(length_pattern,response)
if length.group('amount')!=None or length.group('type')!=None:
    print length.group('amount')
    print length.group('type')

Ok, so I'm just needing this code to be able to take out the words "quarter", "half", "a", or just 1-3 digits. And store that in the amount named group.

Then take out the word "minute", "hour", or "day" and store that in the type group.

import re
f = "(?P<amount>[\d]{1,3}|(quarter)|(half)|(a[n]?))?[.]*(?P<type>(minute)|(hour)|(day)[s]?)?"
find = re.search(r'(?P<amount>[\d]{1,3}|((.*))|', f)
do = find.group(1)
d = re.sub(do, '', f)
print "We taked out the word : %s" % do

and etc with other words

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM