【问题标题】:Extracting a string from a file in Python and include the related value在 Python 中从文件中提取字符串并包含相关值
【发布时间】:2021-09-18 10:25:07
【问题描述】:

有谁知道我如何从文本文件中提取已知字符串“name:”并提取最长可达 12 个字符的相关值?

例如,字符串在文件“test”中并包含:

h2. abc value\r\n * Name: name123\r\n\r\ details more words

如果键 Name: 始终相同但值 name123 一直在变化,我将如何仅提取值 Name: name123

import re
import sys
import string

with open('file') as theFile
  r = theFile.read()
print(r)

theName = re.compile(r'Name:')
mod1 = theName.search(r)
print(mod1)

输出:

<re.Match object; span(23, 33) match='Name:'>

我如何只返回结果“名称:”+“名称123”?

【问题讨论】:

    标签: python regex string bash


    【解决方案1】:

    使用捕获组捕获Name: 之后的所有内容。

    theName = re.compile(r'Name:\s*(.*)')
    mod1 = theName.search(r)
    if mod1:
        print(mod1.group(1))
    

    \s* 将跳过Name: 之后的空格,.* 将匹配该行的其余部分。括号捕获该匹配项。

    【讨论】:

    • 谢谢巴尔玛!但是,如果我希望搜索只捕获“详细信息”一词而不是整行呢?
    • 行结束于\r\n
    • 太好了,这就是我要找的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    相关资源
    最近更新 更多