python - 无法从 python 3 中的输入文件中找到子字符串

标签 python python-2.7 python-3.x python-unicode

我正在尝试从输入文件中查找格式。但有时如果我使用 'r' 则找不到匹配项,有时还会出现 unicode 错误。

def extract_files(filename):
    file = open(filename, 'r')
    text = file.read()
    files_match = re.findall('<Compile Include="src\asf\preprocessor\string.h">', text)
    if not files_match:
        sys.stderr.write('no match')
        sys.exit()
    for f in files_match:
        print(f)

最佳答案

看起来您正试图在<Compile Include="之后拉动所有的弦。直到 "> 。我们可以做到这一点,但请注意,这可能会在边缘情况下崩溃!

import re

def extract_files(filename):
    with open(filename,'r') as file:
        text = file.read
    matches = re.findall(r'(?<=<Compile Include=")[-.A-Za-z\\]+(?=")', text)
    # finds all pathnames that contain ONLY lowercase or uppercase letters,
    # a dash (-) or a dot (.), separated ONLY by a backslash (\)
    # terminates as soon as it finds a double-quote ("), NOT WHEN IT FINDS A
    # SINGLE QUOTE (')
    if not matches:
        sys.stderr.write("no match")
        sys.exit()
    for match in matches:
        print(match)

关于python - 无法从 python 3 中的输入文件中找到子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22233979/

相关文章:

python - 使用 MultiIndex 时如何将此 Pandas 列类型保留为日期时间?

python - pivot_table 没有要聚合的数字类型

python - 银行交易分类的 Tensorflow 实现

Python: "if not any"的问题

python - Boost Python Numpy - 未定义的初始化引用

python - 这是我的代码。我正在尝试获取整数的用户输入,通过利用映射的函数并返回立方结果列表

python - 如何使用 Python Chameleon 指定 html5 文档类型?

python - 如何消除Python中subprocess.Popen的标准输出?

python - 写入 CSV 文件时不带双引号

python - 找不到 Python 代码中的错误