正则表达式搜索CSV中的行以查找首次匹配时挂断的字符

时间:2018-11-02 15:53:43

标签: regex python-2.7 openpyxl

我是脚本新手,所以我的代码可能有点混乱,我事先表示歉意。

我正在尝试遍历CSV并使用openpyxl将其写入excel工作簿。但是在我写它之前,我要进行一些检查以确定将行写到哪张纸上。

该行具有以下内容:“ KB4462941”,“ kb / 9191919”,“ kb -919”,“ sdfklKB91919”。

我正在尝试将“ KB”后面的第一个数字拉出,然后在发现非数字字符后停止读取字符。找到一个,然后运行一个查询数据库的单独函数。该功能有效。

我遇到的问题是,一旦找到第一个KB:KB4462941,它将挂断并多次遍历该KB,直到最后一次出现在该行中,然后程序结束。

不幸的是,KB字符在行中没有默认位置,并且KB和第一个数字之间没有默认字符数。

我的代码:

with open('test.csv') as file:
    reader = csv.reader(file, delimiter = ',')
    for row in reader:
        if str(row).find("SSL") != -1:
            ws = book.get_sheet_by_name('SSL')
            ws.append(row)
        else:
            mylist = list(row)
            string = ''.join(mylist)
            tmplist = list()
            resultlist = list()
            pattern = 'KB.*[0-9]*'
            for i in mylist:
                tmplist += re.findall(pattern, i, re.IGNORECASE)
            for i in tmplist:
                resultlist += re.findall('[0-9]*', i)
            for i in resultlist:
                if len(i) > 4:
                    print i
                    if dbFunction(i) == 1:
                        ws = book.get_sheet_by_name('Found')
                        ws.append(row)
                else:
                    ws = book.get_sheet_by_name('Nothing')
                    ws.append(row)

output: 
1st row is skipped
2nd row is in the right place
3rd and 4th row in the right place
5th row is written for the next nine 9 rows.
never gets to the following 3 rows.

0 个答案:

没有答案