0

I have to find an expression in a text file like : StartTime="4/11/2013 8:11:20:965" and EndTime="4/11/2013 8:11:22:571"

So I used the regex expression

r'(\w)="(\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{1,2}:\d{1,2}:\d{2,3})"'

Thanks again to eumiro for his help earlier (Retrieve randomly preformatted text from Text File)

But I can't find anything in my file, and I checked it was there.

I can't go trhough 'GetDuration lvl 1' with it actually.

I tried to simplify my regex as r'(\d)', and it worked to lvl 4, so I thought it could be and issue with eventually protected " but I didn't see anything about this in python doc.

What am I missing ?

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
4

2 回答 2

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

    ...

for x in str(something)意味着您正在something逐个字符地迭代(一次一个字符= 1 个长度str),并且没有正则表达式可以与之匹配。

于 2013-04-24T14:31:43.650 回答
1

也许这个 exp 应该有帮助:

"(\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,您一次只输入一个字符,使用正则表达式不是一个好主意。

于 2013-04-24T14:31:47.563 回答