weixin_39721336 2025-01-09 17:00 采纳率: 78.6%
浏览 8
已结题

python正则表达式无法获取正确结果

a='''
interface 50|100GE2/0/0
 port-speed 100GE
 description [50|100GE2/0/0]-[100G]
 undo shutdown
 eth-trunk 100
 undo dcn
#
'''
import re

b='50|100GE2/0/0'
interface_block_pattern = re.compile(r"(interface {}.*?#)".format(b),re.DOTALL)
interface_block_match = interface_block_pattern.search(a)
print(interface_block_match.group())

为啥输出的不是整个a,而是‘interface 50’
我python版本是3.11.5

  • 写回答

1条回答 默认 最新

  • 道友老李 JWE233286一种基于机器视觉的水表指针读数识别及修正的方法 专利发明者 2025-01-09 17:01
    关注
    让【道友老李】来帮你解答,本回答参考gpt编写,并整理提供,如果还有疑问可以点击头像关注私信或评论。
    如果答案让您满意,请采纳、关注,非常感谢!
    问题出在正则表达式的写法上。在使用`re.compile`方法编译正则表达式时,需要正确设置匹配模式,最好使用`re.S`(或`re.DOTALL`)模式以匹配多行文本。另外,正则表达式中的`.*?`可能造成非贪婪匹配,只匹配到第一个满足条件的子串。 下面是修改后的代码:
    import re
    a = 'interface 50|100GE2/0/0 port-speed 100GE description [50|100GE2/0/0]-[100G] undo shutdown eth-trunk 100 undo dcn#'
    b = '50|100GE2/0/0'
    interface_block_pattern = re.compile(r'(interface {}.*?#)'.format(re.escape(b)), re.DOTALL)
    interface_block_match = interface_block_pattern.search(a)
    print(interface_block_match.group())
    

    这样就会输出整个字符串a中匹配到的内容,而不仅仅是'interface 50'。 希望这能帮助到你解决问题。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 1月17日
  • 已采纳回答 1月9日
  • 创建了问题 1月9日