python - 使用Python正则表达式搜索包含字符的句子

标签 python regex

我正在使用 Python 正则表达式搜索包含字符的句子。 但我找不到我想要的句子。 请帮助我

正则表达式.py

opfile = open(file.txt, 'r')
contents = opfile.read()
opfile.close()

index = re.findall(r'\[start file\](?:.|\n)*\[end file\]', contents)
item = re.search(r'age.*', str(index))

file.txt(示例)

[start file]
name:      steve
age:       23
[end file]

结果

<re.Match object; span=(94, 738), match='age:               >

未打印年龄

最佳答案

这里有几个问题:

  • str(index) 返回字符串列表的字符串文字表示,这使得进一步处理结果变得困难
  • (?:.|\n)* 是一个非常消耗资源的结构,仅使用 .re.Sre.DOTALL 选项
  • 如果您打算查找单个匹配项,请使用 re.search,而不是 re.findall

这是一个可能的解决方案:

match = re.search(r'\[start file].*\[end file]', contents, re.S)
if match:
    match2 = re.search(r"\bage:\s*(\d+)", match.group())
    if match2:
        print(match2.group(1))

输出:

23

如果您想在输出中获取age,请使用match2.group()

关于python - 使用Python正则表达式搜索包含字符的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72669722/

相关文章:

python - 与 map 函数相比,Python 中的嵌套 for 循环

mysql - 区分大小写的 RLIKE

python - 测试 flask ——避免循环导入

python - 如何使用 MatPlotLib 将 Pandas 中的分箱计数显示为热图?

jquery - 使用 jquery.validator.addMethod 时允许使用破折号的正确正则表达式是什么?

ruby-on-rails - 正则表达式从字符串中删除字符

python - 我如何通过正则表达式捕获它?

regex - 为什么 Eclipse 在 Mac OSX 上找不到正则表达式?

python - 为 Django 网站记录在线用户的快照(postgresql 后端,nginx 网络服务器)

python - 每次我在 Python 中将数据帧保存为 csv 时,Pandas 都会创建一个新列