在文本文件中的特定字符串搜索期间使用Python正则表达式
我必须在文本文件中找到一个表达式,如:在文本文件中的特定字符串搜索期间使用Python正则表达式,python,regex,Python,Regex,我必须在文本文件中找到一个表达式,如:StartTime=“4/11/2013 8:11:20:965”和EndTime=“4/11/2013 8:11:22:571” 所以我用了正则表达式 r'(\w)="(\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{1,2}:\d{1,2}:\d{2,3})"' 再次感谢eumiro早些时候的帮助() 但是我在我的档案里找不到任何东西,我检查了一下它在那里 事实上,我不能用它去尝试“持续时间1级” 我试图将我的正则表达式简化为r'(\
StartTime=“4/11/2013 8:11:20:965”和EndTime=“4/11/2013 8:11:22:571”
所以我用了正则表达式
r'(\w)="(\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{1,2}:\d{1,2}:\d{2,3})"'
再次感谢eumiro早些时候的帮助()
但是我在我的档案里找不到任何东西,我检查了一下它在那里
事实上,我不能用它去尝试“持续时间1级”
我试图将我的正则表达式简化为r'(\d)
,它适用于第4级,因此我认为它可能最终受到保护“
”,但我在python文档中没有看到任何关于这方面的内容
我错过了什么
Regular_Exp = r'(\w)="(\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{1,2}:\d{1,2}:\d{2,3})"'
def getDuration(timeCode1, timeCode2)
duration =0
c = ''
print 'GetDuration lvl 0'
for c in str(timeCode1) :
m = re.search(Regular_Exp, c)
print 'GetDuration lvl 1'
if m:
print 'GetDuration lvl 2'
for text in str(timeCode2) :
print 'GetDuration lvl 3'
n = re.search(Regular_Exp, c)
if n:
print 'GetDuration lvl 4'
timeCode1Split = timeCode1.split(' ')
timeCode1Date = timeCode1Split[0].split('/')
timeCode1Heure = timeCode1Split[1].split(':')
timeCode2Split = timeCode2.split(' ')
timeCode2Date = timeCode2Split[0].split('/')
timeCode2Heure = timeCode2Split[1].split(':')
timeCode1Date = dt.datetime(timeCode1Date[0], timeCode1Date[1], timeCode1Date[2], timeCode1Heure[0], timeCode1Heure[0], timeCode1Heure[0], tzinfo=utc)
timeCode2Date = dt.datetime(timeCode2Date[0], timeCode2Date[1], timeCode2Date[2], timeCode2Heure[0], timeCode2Heure[0], timeCode2Heure[0], tzinfo=utc)
print 'TimeCode'
print timeCode1Date
print timeCode2Date
duration += timeCode1Date - timeCode2Date
return duration
对于str(something)
中的x,意味着你正在一个字符一个字符地迭代某物(一次一个字符=1个长度str
),没有正则表达式可以与之匹配。也许这个经验应该有帮助:
"(\w+?)=\"(.+?)\""
使用:
>>> string = u'StartTime="4/11/2013 8:11:20:965" and EndTime="4/11/2013 8:11:22:571"'
>>> regex = re.compile("(\w+?)=\"(.+?)\"")
# Run findall
>>> regex.findall(string)
[(u'StartTime', u'4/11/2013 8:11:20:965'), (u'EndTime', u'4/11/2013 8:11:22:571')]
另外,对于str中的c(timeCode1)
,请尝试打印c
,一次打印一个字符,使用正则表达式不是一个好主意。谢谢您的帮助,我将尝试其他方法:)
>>> string = u'StartTime="4/11/2013 8:11:20:965" and EndTime="4/11/2013 8:11:22:571"'
>>> regex = re.compile("(\w+?)=\"(.+?)\"")
# Run findall
>>> regex.findall(string)
[(u'StartTime', u'4/11/2013 8:11:20:965'), (u'EndTime', u'4/11/2013 8:11:22:571')]