Python正则表达式在文本中的特定字符串搜索期间的使用

2024-06-26 13:23:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须在文本文件中找到一个表达式,如:StartTime="4/11/2013 8:11:20:965" and 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早些时候的帮助(Retrieve randomly preformatted text from Text File

但我在我的档案里找不到任何东西,我查过了。你知道吗

我真的不能用它去尝试“GetDuration 1级”。你知道吗

我试图将regex简化为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

Tags: splitdurationprintregularexplvlgetdurationtimecode1heure
2条回答

也许这个实验应该有帮助:

"(\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')]

另外,for c in str(timeCode1),尝试打印c,一次只打印一个字符,使用regex不是个好主意。。你知道吗

for c in str(timeCode1) :
    m = re.search(Regular_Exp, c)

    ...

for x in str(something)意味着要逐字符迭代something(一次一个字符=1个长度str),没有正则表达式可以与之匹配。你知道吗

相关问题 更多 >