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

Python:使用Python从一行中提取以数字开头的匹配单词,python,regex,shell,Python,Regex,Shell,我想阅读文本文件,在下面的文本中找到以5开头的单词 “状态”:“OK”}],“PhysicalLocationString”:“rack1/chassis_u1/cpu0/pcie_slot3”,“Physloc”:“000300010010005”,“Placeholder NetworkDeviceFunctions”:[{“FC HBA 1”:“51:40:2E:C0:01:C9:53:E8”},{“FC HBA 2”:“51:40:2E:C0 01:C9:53:EA”}],“零件号”:“

我想阅读文本文件,在下面的文本中找到以5开头的单词

“状态”:“OK”}],“PhysicalLocationString”:“rack1/chassis_u1/cpu0/pcie_slot3”,“Physloc”:“000300010010005”,“Placeholder NetworkDeviceFunctions”:[{“FC HBA 1”:“51:40:2E:C0:01:C9:53:E8”},{“FC HBA 2”:“51:40:2E:C0 01:C9:53:EA”}],“零件号”:“P9D94A”,“序列号”:“MY57470DS8”,“状态”:“健康状况”:“OK”,“健康状况”:“OK”,“健康状况”:”“已启用”}

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

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,后跟除引号以外的任何内容,然后在其后的引号处结束。分组将提取您想要的号码。

您可以尝试以下方法:

" ".join(e for e in your_string.split('"') if e.startswith("5"))

谢谢你的编辑ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ三千

或:

输出:

51:40:2E:C0:01:C9:53:E8 51:40:2E:C0:01:C9:53:EA
在换行符中:

print("\n".join(filter(lambda x: x.startswith('5'),your_string.split('"'))))

这看起来像是JSON内容,因此您应该在这里使用JSON解析器,而不是纯正则表达式解决方案“^SyntaxError:无效的语法很抱歉!我用更好的引语修正了它。非常感谢你们。下一行怎么写?比如51:40:2E:C0:01:C9:53:E8 51:40:2E:C0:01:C9:53:EA第一行应该是51:40:2E:C0:01:C9:53:E8,第二行应该是51:40:2E:C0:01:C9:53:EA@RamKrishna编辑我的answer@RamKrishna很高兴我能帮助您,您不需要
列表
。只需执行
print(“\n”.join(filter(lambda x:x.startswith('5'),您的字符串.split('”))
print("\n".join(filter(lambda x: x.startswith('5'),your_string.split('"'))))