[Python] python regex to match multiple words in a line without going to the next line

Discussão em 'Python' iniciado por Stack, Março 3, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing a parser to parse the below output:

    admin@str-s6000-on-5:~$ show interface status Ethernet4
    Interface Lanes Speed MTU Alias Vlan Oper Admin Type Asym PFC
    --------------- ----------- ------- ----- ------------ ------ ------ ------- -------------- ----------
    Ethernet4 29,30,31,32 40G 9100 fortyGigE0/4 trunk up up QSFP+ or later off
    PortChannel0001 N/A 40G 9100 N/A routed up up N/A N/A
    PortChannel0002 N/A 40G 9100 N/A routed up up N/A N/A
    PortChannel0003 N/A 40G 9100 N/A routed up up N/A N/A
    PortChannel0004 N/A 40G 9100 N/A routed up up N/A N/A


    I have made an attempt to write a regex to match all the fields as below

    (\S+)\s+([\d,]+)\s+(\S+)\s+(\d+)\s+(\S+)\s+(\S+)\s+([up|down])+\s+([up|down]+)\s+([\w\s+?]+)\s+(\S+)


    I'm able to get upto Admin column correctly. The column Type contains multiple words so i have used the pattern ([\w\s+?]+) hoping it will match multiple workds seperated by one space with + being optional followed by (\S+) to match the last column. The problem that I face is, regex ([\w\s+?]+) spawns over multiple lines and it gives me an output as below

    Ethernet4 29,30,31,32 40G 9100 fortyGigE0/4 trunk up up QSFP+ or later off PortChannel0001 N/A

    I see that \s matches the new line as well. how to restrict that not to match the new line? could someone pls help me to clarify.

    I looked at this space Regex for one or more words separated by spaces but that is not helping me either. can someone help me to understand this better?

    Continue reading...

Compartilhe esta Página