简体   繁体   English

如何使Python正则表达式模式在开头或某个字符串的开头匹配某个字符?

[英]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 到目前为止,这是我在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. 好的,所以我只需要此代码即可取出单词“ quarter”,“ half”,“ a”或仅1-3个数字。 And store that in the amount named group. 并将其存储在名为group的数量中。

Then take out the word "minute", "hour", or "day" and store that in the type 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

and etc with other words 等用其他词

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python:用于匹配多行模式的正则表达式(应用于字符串的开头) - python: regex to match pattern on multiple lines (apply to start of string) 需要正则表达式帮助:如果某些字符串不是以某些子模式开头并且某些字符不应该存在,则匹配 - Need regex help: Match if certain string doesn't start with certain sub-patterns AND certain character should not be there 正则表达式仅在行不以字符开头时才匹配模式 - Regex to match pattern only if the line does not start with a character 在python中,如何用QRegExp匹配以#字符开头的字符串? - In python, how to match a string with QRegExp that may start with # character? Python正则表达式:如何在选择中匹配字符串的开头? - Python regex: How can I match start of string in a selection? python正则表达式匹配字符串不以 - python regex match string does not start with Python正则表达式 - 匹配和开始() - Python Regex - Match and Start() 如何编写正则表达式模式以匹配字符串结尾或字符串开头的货币符号 - How to write a regex pattern to match string with currency sybol at end OR start of string 如何仅匹配特定字符的正则表达式模式 - How to match regex pattern only up to certain character Ansible 或 Python,如何在列表中使用 regex_findall 来返回以特定模式开头的单词 - Ansible or Python, how to use regex_findall on a list to return words that start with a certain pattern
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM