python 正则表达式 用法总结 例子

本文介绍如何使用正则表达式从网络配置文件中提取关键信息,包括DNS服务器、网络接口类型、IP地址和子网掩码等,通过Python代码示例展示了不同场景下正则表达式的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面的 正则表达式 都是一行一行的解析的,
如果你有一大段话,要解析,可以将这一大段话,分成一行,一行的 ,再解析

例子1:
	import re
	mac = "com1 com2 com3 com4"
    pattern = re.compile(r'com\d', re.IGNORECASE)
    result = pattern.findall(mac)
    print result
例子2:
    with open("/etc/resolv.conf", 'r') as f:
        lines = f.readlines()

    dns_list = []
    for line in lines :

        ret = re.match(r'^[\s]*nameserver[\s]+(.*)', line)

        if ret:
            dns_list.append(ret.group(1).strip())

例子3:
    try:
        with open("/etc/network/interfaces", 'r') as f:
            lines = f.readlines()
    except:
        print 'error'

    print type(lines)

    for line in lines:

        result = re.match(r"^[\s]*iface[\s]+eth0[\s]+inet[\s]+(.*)", line)

        if result:
            print 'hello'
            tt = result.group(1)
            tt = tt.strip()
            print tt
            if tt == 'static':
                print 'helloppp'
                net_info['ethernet']['ip_type'] = 'static'

            if tt == 'dhcp':
                print 'dd dhcp'
                net_info['ethernet']['ip_type'] = 'dhcp'
                break

解析ifconfig
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import json
import re


def test():
    p = os.popen("ps -ef | grep modbus_task.py | grep -v grep | awk '{print $6}'")
    mac = p.read().strip()
    p.close()

    pattern = re.compile(r'com\d', re.IGNORECASE)
    result = pattern.findall(mac)
    print result


if __name__ == "__main__":

    p = os.popen("ifconfig")
    msg = p.read().strip()
    p.close()

    print msg

    list = msg.split("\n")

    for item in list:
        print item


    data = re.findall(r'(\w*)[\s]+Link encap', msg)

    # ['eth0', 'lo', 'ppp0']



    print data

    print '+++++++++++++++++++++++'

    data = re.split(r'(\w+)\s+Link encap', msg)

    print data
    print '--------------------------'
    for item in data:
        print '------------1111---------------'
        print item
        print '------------33333---------------'

    if 'eth0' in data:
        print 'have eth0'

    if 'ppp0' in data:
        print 'have ppp0'


    print len(data)


    msg_info = dict()

    i = 1
    while i < len(data):

        msg_info[data[i]] = data[i+1]
        i = i + 2

        print i

    print '8888888888888888888888'
    for k,v in msg_info.items():
        print 'key',k
        print 'v=',v



    list = msg_info['eth0'].split('\n')
    print '777777777777777777'
    print list
    print '9999999999999'
    for line in list:

        ret = re.match(r'.*\s+HWaddr\s+(.+)\s+', line)

        if ret :
            print 'HWaddr:'
            print ret.group(1)
            break

    for line in list:

        ret = re.match(r'.*inet addr:\s*([\d\.]+)\s+', line)

        if ret :
            print 'inet addr:'
            print ret.group(1)
            break

    for line in list:

        ret = re.match(r'.*\s*Mask:\s*([\d\.]+)\s*', line)

        if ret :
            print 'mask:'
            print ret.group(1)
            break




    list = msg_info['ppp0'].split('\n')
    print '777777777777777777'
    print list
    print '9999999999999'
    for line in list:

        ret = re.match(r'.*\s*P-t-P:\s*(.+)\s+', line)

        if ret :
            print 'P-t-P:'
            print ret.group(1)
            break

    for line in list:

        ret = re.match(r'.*inet addr:\s*([\d\.]+)\s+', line)

        if ret :
            print 'inet addr:'
            print ret.group(1)
            break

    for line in list:

        ret = re.match(r'.*\s*Mask:\s*([\d\.]+)\s*', line)

        if ret :
            print 'mask:'
            print ret.group(1)
            break

数据:

eth0      Link encap:Ethernet  HWaddr 06:CF:CB:9A:46:CE  
          inet addr:192.168.99.207  Bcast:0.0.0.0  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1972782 errors:1 dropped:1529 overruns:0 frame:1
          TX packets:309982 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:632113023 (602.8 MiB)  TX bytes:55422636 (52.8 MiB)
          Interrupt:30 Base address:0x8000 

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:62 errors:0 dropped:0 overruns:0 frame:0
          TX packets:62 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:4472 (4.3 KiB)  TX bytes:4472 (4.3 KiB)

ppp0      Link encap:Point-to-Point Protocol  
          inet addr:10.214.192.238  P-t-P:10.64.64.64  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:10218 errors:0 dropped:0 overruns:0 frame:0
          TX packets:10307 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:3 
          RX bytes:591744 (577.8 KiB)  TX bytes:824118 (804.8 KiB)
eth0      Link encap:Ethernet  HWaddr 06:CF:CB:9A:46:CE  
          inet addr:192.168.99.207  Bcast:0.0.0.0  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1972782 errors:1 dropped:1529 overruns:0 frame:1
          TX packets:309982 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:632113023 (602.8 MiB)  TX bytes:55422636 (52.8 MiB)
          Interrupt:30 Base address:0x8000 

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:62 errors:0 dropped:0 overruns:0 frame:0
          TX packets:62 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:4472 (4.3 KiB)  TX bytes:4472 (4.3 KiB)

ppp0      Link encap:Point-to-Point Protocol  
          inet addr:10.214.192.238  P-t-P:10.64.64.64  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:10218 errors:0 dropped:0 overruns:0 frame:0
          TX packets:10307 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:3 
          RX bytes:591744 (577.8 KiB)  TX bytes:824118 (804.8 KiB)
['eth0', 'lo', 'ppp0']
+++++++++++++++++++++++
['', 'eth0', ':Ethernet  HWaddr 06:CF:CB:9A:46:CE  \n          inet addr:192.168.99.207  Bcast:0.0.0.0  Mask:255.255.255.0\n          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1\n          RX packets:1972782 errors:1 dropped:1529 overruns:0 frame:1\n          TX packets:309982 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:1000 \n          RX bytes:632113023 (602.8 MiB)  TX bytes:55422636 (52.8 MiB)\n          Interrupt:30 Base address:0x8000 \n\n', 'lo', ':Local Loopback  \n          inet addr:127.0.0.1  Mask:255.0.0.0\n          UP LOOPBACK RUNNING  MTU:65536  Metric:1\n          RX packets:62 errors:0 dropped:0 overruns:0 frame:0\n          TX packets:62 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:0 \n          RX bytes:4472 (4.3 KiB)  TX bytes:4472 (4.3 KiB)\n\n', 'ppp0', ':Point-to-Point Protocol  \n          inet addr:10.214.192.238  P-t-P:10.64.64.64  Mask:255.255.255.255\n          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1\n          RX packets:10218 errors:0 dropped:0 overruns:0 frame:0\n          TX packets:10307 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:3 \n          RX bytes:591744 (577.8 KiB)  TX bytes:824118 (804.8 KiB)']
--------------------------
------------1111---------------

------------33333---------------
------------1111---------------
eth0
------------33333---------------
------------1111---------------
:Ethernet  HWaddr 06:CF:CB:9A:46:CE  
          inet addr:192.168.99.207  Bcast:0.0.0.0  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1972782 errors:1 dropped:1529 overruns:0 frame:1
          TX packets:309982 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:632113023 (602.8 MiB)  TX bytes:55422636 (52.8 MiB)
          Interrupt:30 Base address:0x8000 


------------33333---------------
------------1111---------------
lo
------------33333---------------
------------1111---------------
:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:62 errors:0 dropped:0 overruns:0 frame:0
          TX packets:62 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:4472 (4.3 KiB)  TX bytes:4472 (4.3 KiB)


------------33333---------------
------------1111---------------
ppp0
------------33333---------------
------------1111---------------
:Point-to-Point Protocol  
          inet addr:10.214.192.238  P-t-P:10.64.64.64  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:10218 errors:0 dropped:0 overruns:0 frame:0
          TX packets:10307 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:3 
          RX bytes:591744 (577.8 KiB)  TX bytes:824118 (804.8 KiB)
------------33333---------------
have eth0
have ppp0
7
3
5
7
8888888888888888888888
key lo
v= :Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:62 errors:0 dropped:0 overruns:0 frame:0
          TX packets:62 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:4472 (4.3 KiB)  TX bytes:4472 (4.3 KiB)


key ppp0
v= :Point-to-Point Protocol  
          inet addr:10.214.192.238  P-t-P:10.64.64.64  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:10218 errors:0 dropped:0 overruns:0 frame:0
          TX packets:10307 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:3 
          RX bytes:591744 (577.8 KiB)  TX bytes:824118 (804.8 KiB)
key eth0
v= :Ethernet  HWaddr 06:CF:CB:9A:46:CE  
          inet addr:192.168.99.207  Bcast:0.0.0.0  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1972782 errors:1 dropped:1529 overruns:0 frame:1
          TX packets:309982 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:632113023 (602.8 MiB)  TX bytes:55422636 (52.8 MiB)
          Interrupt:30 Base address:0x8000 


777777777777777777
[':Ethernet  HWaddr 06:CF:CB:9A:46:CE  ', '          inet addr:192.168.99.207  Bcast:0.0.0.0  Mask:255.255.255.0', '          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1', '          RX packets:1972782 errors:1 dropped:1529 overruns:0 frame:1', '          TX packets:309982 errors:0 dropped:0 overruns:0 carrier:0', '          collisions:0 txqueuelen:1000 ', '          RX bytes:632113023 (602.8 MiB)  TX bytes:55422636 (52.8 MiB)', '          Interrupt:30 Base address:0x8000 ', '', '']
9999999999999
HWaddr:
06:CF:CB:9A:46:CE 
inet addr:
192.168.99.207
mask:
255.255.255.0
777777777777777777
[':Point-to-Point Protocol  ', '          inet addr:10.214.192.238  P-t-P:10.64.64.64  Mask:255.255.255.255', '          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1', '          RX packets:10218 errors:0 dropped:0 overruns:0 frame:0', '          TX packets:10307 errors:0 dropped:0 overruns:0 carrier:0', '          collisions:0 txqueuelen:3 ', '          RX bytes:591744 (577.8 KiB)  TX bytes:824118 (804.8 KiB)']
9999999999999
P-t-P:
10.64.64.64 
inet addr:
10.214.192.238
mask:
255.255.255.255

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值