简体   繁体   English

正则表达式无法扩展以在Python中找到相似的模式

[英]Regular expression cant be extended to find similar pattern in Python

i am trying to match a pattern of ( dd/yy - dd/yy ) or (0d/yyyy - 0d/yyyy). 我正在尝试匹配(dd / yy-dd / yy)或(0d / yyyy-0d / yyyy)的模式。 Any possible combinations of the similar pattern in the text. 文本中相似模式的任何可能组合。

My text is: 我的文字是:

 text  = ''' 09/14 - 18/18 some text 09/13 – 04/14 '''

My pattern is: 我的模式是:

 r"b([\d]{1,2}[\s/-]+[\d]{2,4}[-:\s.]+\d{1,2}[\s/-]+[\d]{2,4}[\s/-]+)"

It successfully matches 09/14 - 18/18 . 它成功匹配09/14-18/18。 But not matching 09/13 – 04/14 in the text. 但与文本中的09/13 – 04/14不匹配。 Another doubt I am having is , if I want to check if say "09/14 - " is followed by a "word (any word in a list)" or a pattern like "dd/yy or dd/yyyy" what should I do. 我遇到的另一个疑问是,如果我想检查是否说“ 09/14-”后跟“单词(列表中的任何单词)”或“ dd / yy或dd / yyyy”之类的模式,该怎么办?做。 My point is if it matches any of the either check I have to pick that with "09/14". 我的意思是,如果它与我必须用“ 09/14”选择的任一支票相匹配。 ie, "09/14 - word" if it matches or "09/14 - dd/yyyy" if it matches . 即,如果匹配则为“ 09/14-word”,如果匹配则为“ 09/14-dd / yyyy”。

It successfully matches 09/14 - 18/18 . 它成功匹配09/14-18/18。 But not matching 09/13 – 04/14 in the text. 但与文本中的09/13 – 04/14不匹配。

Because - and are different characters. 因为-是不同的字符。

\b([\d]{1,2}[\s/-]+[\d]{2,4}[-:–\s.]+\d{1,2}[\s/-]+[\d]{2,4}[\s/-]+)

DEMO DEMO

Use this if you don't want to capture the spaces following the match. 如果您不想捕获比赛后的空格,请使用此选项。

\b([\d]{1,2}[\s/-]+[\d]{2,4}[-:–\s.]+\d{1,2}[\s/-]+[\d]{2,4})\b

DEMO DEMO

if I want to check if say "09/14 - " is followed by a "word (any word in a list)" or a pattern like "dd/yy or dd/yyyy" what should I do. 如果我想检查是否说“ 09/14-”后跟“单词(列表中的任何单词)”或“ dd / yy或dd / yyyy”之类的模式,该怎么办。

\b[\d]{1,2}[\s/-]+[\d]{2,4}[-:–\s.]+(?:\d{1,2}[\s/-]+[\d]{2,4}|\w)

DEMO DEMO

>>> text  = ''' 09/14 - 18/18 some text 09/13 – 04/14 '''
>>> re.findall(r'\b([\d]{1,2}[\s/-]+[\d]{2,4}[-:–\s.]+\d{1,2}[\s/-]+[\d]{2,4})\b', text)
['09/14 - 18/18', '09/13 – 04/14']

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

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