Python Re:测试过的正则表达式模式不返回匹配项

瑞安

使用下面的python我试图找到带有markdown文件的特定标题

import re

source_file = open('readme.md')

#Defines variables containing the headings as Regex searches

product_name = re.compile('(?mi)^#+[^\S\n]product.*name')
product_version = re.compile('(?mi)^#+[^\S\n]product.*version')
product_description = re.compile('(?mi)^#+[^\S\n]product.*description')

#Adds the required headings to a list
headings = [product_name, product_version, product_description]

#Opens the readme, searches for the specified headings, then uses print_section to print the content under the headings
with open('readme.md') as file:
    for x in headings:
        content = x.search(file.read()).group(0)
        print(content)

readme.md文件包含以下占位符文本

# Product Name
Test Product
## Product Version
0.01
## Product Description
A short overview of what this product is; what it does; and what its intended use case is
# Specifications
## Networking
the quick brown fox jumped over the lazy dog
## Data Usage
This is line one of the sample
This is line two of the sample

我从运行此文件得到的响应是:

# Product Name
Traceback (most recent call last):
  File "sample.py", line 16, in <module>
    content = x.search(file.read()).group(0)
AttributeError: 'NoneType' object has no attribute 'group'

所以我认为第二个和第三个Regex模式存在问题。但是在正则表达式测试器中,它们似乎可以正确匹配我无法真正发现这些模式与第一个成功的模式之间的任何区别,甚至尝试交换markdown文件中内容的顺序,但仍然只有product_name匹配。

伊良口

仅读取一次文件,然后搜索:

with open('readme.md') as file:
    f = file.read()
    for x in headings:
        content = x.search(f).group(0)
        print(content)

Python一旦read()到达文件末尾(基本上是在第一次迭代后),它将继续返回空字符串。而且,由于搜索空字符串,您会不断收到NoneType错误。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Python正则表达式与模式不匹配

Python正则表达式匹配返回所有匹配项

正则表达式在测试器中匹配良好,但在 Python 代码中不匹配

从 Python 的 re 模块中获取正则表达式匹配和其余(不匹配)

Python正则表达式选择所有与模式不匹配的元素

Python正则表达式-不包含字符串的匹配模式

Python正则表达式拆分多个匹配项

Python正则表达式输出多个匹配项

Python在有效的正则表达式上未返回任何匹配项

在python中使用正则表达式返回唯一匹配项

Python正则表达式:在一行而不是列表中返回匹配项?

python正则表达式,只返回第一个匹配项

如果找不到匹配项,正则表达式会返回python什么?

正则表达式的正则表达式在Python中不匹配

Python正则表达式:贪婪模式返回多个空匹配

尝试匹配文本中的正则表达式模式总是返回无 Python

python-正则表达式以匹配最后的模式

在 Python 中匹配多行正则表达式模式

正则表达式模式无法在python中匹配

python中的负正则表达式模式匹配

python中的正则表达式模式匹配

Python逐行匹配正则表达式模式

使用正则表达式python进行模式匹配

python正则表达式模式匹配

Python正则表达式re.sub()不匹配并按预期替换

python的re:如果字符串包含正则表达式模式,则返回True

python的re:如果字符串包含正则表达式模式,则返回True

(Python 3) - 正则表达式问题不返回匹配

Python正则表达式括号匹配不返回正确的子字符串