簡體   English   中英

如何使Python正則表達式模式在開頭或某個字符串的開頭匹配某個字符?

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

到目前為止,這是我在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')

好的,所以我只需要此代碼即可取出單詞“ quarter”,“ half”,“ a”或僅1-3個數字。 並將其存儲在名為group的數量中。

然后取出單詞“ minute”,“ hour”或“ day”並將其存儲在類型組中。

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

等用其他詞

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM