簡體   English   中英

Python正則表達式在文本文件中的特定字符串搜索期間使用

[英]Python Regex use during specific string search in a text file

我必須在文本文件中找到一個表達式,如: 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的幫助( 從文本文件中隨機檢索預先格式化的文本

但我在我的檔案中找不到任何東西,我檢查過它。

實際上,我無法用它來實現'GetDuration lvl 1'。

我試圖將我的正則表達式簡化為r'(\\d)' ,並且它工作到lvl 4,所以我認為它可能並且最終受到保護的問題"但我在python doc中沒有看到任何關於此的內容。

我錯過了什么?

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
for c in str(timeCode1) :
    m = re.search(Regular_Exp, c)

    ...

for x in str(something)意味着你迭代something逐個字符(一個字符= 1個長度str在時間),並沒有正則表達式可以與匹配。

也許這個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 ,你一次只能輸入一個字符,這對於正則表達式來說不是一個好主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM