Regex 组合正则表达式和已知字符串
这是我目前的代码:Regex 组合正则表达式和已知字符串,regex,python-3.x,Regex,Python 3.x,这是我目前的代码: exp1 = re.compile('((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4})') 但我想实现的是这样的: regMonth = '(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)' exp1 = re.compile(r'(regMonth'+ r'\s?\d{4})') 我该怎么做呢?你可以试试: regMonth = 'Jan|Feb
exp1 = re.compile('((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4})')
但我想实现的是这样的:
regMonth = '(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)'
exp1 = re.compile(r'(regMonth'+ r'\s?\d{4})')
我该怎么做呢?你可以试试:
regMonth = 'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec'
pattern = r'(?i)(?:' + regMonth + r')\s?\d{4}'
像这样:
regMonth = 'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec'
string_1 = 'Jan 1947, dec 3456'
pattern = r'(?i)(?:' + regMonth + r')\s?\d{4}'
y = re.findall(pattern, string_1)
如果在这种情况下打印y,则会得到:
['Jan 1947', 'dec 3456']
这是一个匹配日期的数组。字符串_1是输入字符串,其中包含所需格式的日期
解释-
首先,您可以将模式解释为:
其中:
(?i) - Indicates that the regex is case-insensitive (If you want the user to enter the Month with the first letter being in caps, then remove this)
(?: - Is a non-capturing group containing the month (followed by 'regMonth')
注意-您必须将第二个字符串“\s?\d{4}”也作为原始字符串,否则整个过程会变得一团糟
另外,非捕获组也很重要,否则正则表达式将匹配一月、二月、,十一月,还是十二月?\d{4}。
因此,Dec\s?\d{4}成为一个完全独立的选项,这是不可取的。是的,我尝试过,效果很好,谢谢您的回复。
(?i) - Indicates that the regex is case-insensitive (If you want the user to enter the Month with the first letter being in caps, then remove this)
(?: - Is a non-capturing group containing the month (followed by 'regMonth')