[英]How to match 2 digits in python with string?
I have following options, but all of them return full string. 我有以下选项,但所有选项都返回完整字符串。 I need to remove date at the beginning with regex. 我需要从正则表达式开始删除日期。
d = re.match('^\d{2}.\d{2}.\d{4}(.*?)$', '01.10.2018Any text..')
d = re.match('^[0-9]{2}.[0-9]{2}.[0-9]{4}(.*?)$', '01.10.2018Any text..')
How to do that? 怎么做? Python 3.6 Python 3.6
You could use sub to match the date like pattern (Note that that does not validate a date) from the start of the string ^\\d{2}\\.\\d{2}\\.\\d{4}
and replace with an empty string. 您可以从字符串^\\d{2}\\.\\d{2}\\.\\d{4}
的开头使用sub来匹配日期(例如模式(请注意,这不验证日期)),然后替换为空字符串。
And as @UnbearableLightness mentioned, you have to escape the dot \\.
正如@UnbearableLightness所述,您必须转义点\\.
if you want to match it literally. 如果您想从字面上进行匹配。
import re
result = re.sub(r'^\d{2}\.\d{2}\.\d{4}', '', '01.10.2018Any text..')
print(result) # Any text..
Grab the first group of the match 抢第一局比赛
>>> d = re.match('^\d{2}.\d{2}.\d{4}(.*?)$', '01.10.2018Any text..').group(1)
>>> print (d)
'Any text..'
If you are not sure, if there would be a match, you have to check it first 如果您不确定是否会匹配,则必须先检查一下
>>> s = '01.10.2018Any text..'
>>> match = re.match('^\d{2}.\d{2}.\d{4}(.*?)$', s)
>>> d = match.group(1) if match else s
>>> print(d)
'Any text..'
Use a group to extract the date part: 使用组来提取日期部分:
d = re.match('^(\d{2}.\d{2}.\d{4})(.*?)$', '01.10.2018Any text..')
if d:
print(d.group(1))
print(d.group(2))
Group 0 is the whole string, I added a pair of parentheses in the regex around the date. 组0是整个字符串,我在日期周围的正则表达式中添加了一对括号。 This is group 1. Group 2 is the text after which is what you're after 这是第1组。第2组是文本,后面是您要输入的内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.