Python正则表达式在复杂模式中搜索

2024-04-26 07:11:58 发布

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

我对python很陌生。你知道吗

这对我来说很难。你知道吗

现在我在文件中找到了一些字符串。你知道吗

我有regex,但我不知道如何在python中使用它。它在Eclipse中工作。你知道吗

下面是正则表达式。你知道吗

("|')\w+\1\s*=\s*?\w*?\.?suppkdid

这是我的来源我试过了。你知道吗

import fnmatch, re, os

regex =  ''  #Q1. How could it be possible? 

for root, dirnames, filenames in os.walk('C:\the_file_directory'):
    for filename in fnmatch.filter(filenames, '*.odi'):
        with open(os.path.join(root, filename)) as f:
            for line in f:
                                if regex.search(line) is not None: #Q2. Is it right?
                                    print '=========================='
                                    print 'filename : %s' %filename 
                                    print 'line : %s' %line
                                    print '=========================='

Tags: 文件字符串inforoslineitroot
1条回答
网友
1楼 · 发布于 2024-04-26 07:11:58
regex=re.compile(r"""("|')\w+\1\s*=\s*?\w*?\.?suppkdid""")

您需要创建一个regex编译模式。你知道吗

其实你可以直接用

if re.search(r"""("|')\w+\1\s*=\s*?\w*?\.?suppkdid""",line) is not None:

同时使用

""" 

而不是"',因为它们都在您的模式中。你知道吗

相关问题 更多 >