Python Regex - 如果Statement等于'string'并匹配整行

时间:2018-02-21 02:42:47

标签: python regex python-3.x if-statement

我有一个脚本打印标题行之间的所有行,但它只适用于我的虚拟数据,所以我试图在某个字符串后匹配整行。

说我在文本文件中有这些数据:

  

哑数据

     

index1 0000

     

随机数据

     

index1 0000

     

随机数据

     

index2 0000

脚本能够在索引1之后提取所有行并在索引2之前停止,但只有在索引行与我的if语句中的extactly匹配时才有效。这意味着如果我删除“index1”之后的所有内容它就可以了。所以我尝试使用正则表达式,基于这里阅读python文档https://docs.python.org/3.4/library/re.html

这是我的代码: 它适用于正则表达式部分,如果我将result1和result2替换为我需要的提取字符串。我错过了什么?我用 '。'匹配'index1'之后的所有内容,对吗?

import re

myvar = False
prog = re.compile('.')
result1 = prog.match('index1')
result2 = prog.match('index2')

with open('Sample Test.txt') as f:
    for line in f:
        if result1 in line:
            myvar = True
            print (line)

        elif result2 in line:
            myvar = False
            print (line)

        elif myvar == True:
            print(line)
            continue

当我尝试运行它时,我得到了这个回溯:

  

Traceback(最近一次调用最后一次):文件“C:\ mytest \ test.py”,第10行,in    if result1 in line:TypeError:'in'要求字符串为left>操作数,而不是_sre.SRE_Match

1 个答案:

答案 0 :(得分:1)

你没有正确使用正则表达式......这就是你应该这样做的。

Option Explicit
Public Sub Example()
    Dim rng As Range
    Dim olApp As Object
    Dim Email As Object
    Dim Sht As Excel.Worksheet
    Dim wdDoc As Word.Document

    Set Sht = ActiveWorkbook.Sheets("Dashboard")
    Set rng = Sht.Range("B4:L17")
        rng.CopyPicture Appearance:=xlScreen, Format:=xlPicture

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set olApp = CreateObject("Outlook.Application")
    Set Email = olApp.CreateItem(0)
    Set wdDoc = Email.GetInspector.WordEditor

    With Email
        .To = ""
        .CC = ""
        .BCC = ""
        .Subject = ""
        .Attachments.Add ActiveWorkbook.FullName

         wdDoc.Range.PasteAndFormat Type:=wdChartPicture

'        if need setup inlineshapes hight & width
         With wdDoc
            .InlineShapes(1).Height = 130
         End With

        .Display
    End With

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set Email = Nothing
    Set olApp = Nothing
End Sub