Python:使用python从一行中提取以数字开头的匹配单词

标签 python regex shell

我想读取文本文件并找到下面文本中以 5 开头的单词。

“状态”:“确定”}]、“PhysicalLocationString”:“rack1/chassis_u1/cpu0/pcie_slot3”、“Physloc”:“0003000101010005”、“PlaceholderNetworkDeviceFunctions”:[{“FC HBA 1”:“51: 40:2E:C0:01:C9:53:E8"}, {"FC HBA 2": "51:40:2E:C0:01:C9:53:EA"}]}}, "零件编号": "P9D94A", "序列号": "MY57470DS8", "状态": {"Health": "OK", "HealthRollup": "OK", "State": "Enabled"}}

我在另一个文件中的输出应该是

51:40:2E:C0:01:C9:53:E8 51:40:2E:C0:01:C9:53:EA

这是我的代码:

    import re
    import sys
    import os

    #get line
    with open('/root/SDFlex/work/cookbooks/ilorest/files/OP.txt', 'r') as file:
    for line in file:
    re.findall(r'\b[s]:\w+', line)
    matchedLine = line
        break


    #and write it to the file
    with open('/root/SDFlex/work/cookbooks/ilorest/files/file.txt', 'w') as 
    file:
         file.write(matchedLine)

请帮忙

最佳答案

使用模式

pattern = '"(5[^"]+)"'
re.findall(pattern, your_string)

它将搜索引号 ",后跟 5,后跟除引号之外的任何内容,然后以引号结束。分组将提取您想要的数字。

关于Python:使用python从一行中提取以数字开头的匹配单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51644378/

相关文章:

python - 什么是类似于 sum() 的减法函数,用于减去列表中的项目?

javascript - javascript 中的 Value.replace 不允许特定字符

bash - 使用sshpass循环时在哪里放置<< EOF?

linux - 仅特定用户 Shell 脚本的 USERID、PID、TIME 和 COMMAND

bash - "set -euo pipefail"对 eval 有影响吗?

python - 如何让python只显示可整除的数字

python - gettext:如何避免 unicode 字符失败?

python - 无法理解 [Errno 111] 连接被拒绝

javascript - 正则表达式:匹配一个子字符串,但稍后排除另一个子字符串

python - 如何使用 beautifulsoup 从 html 页面抓取纬度/经度数据