1. 程式人生 > >正則表示式匹配案例

正則表示式匹配案例

import re
import time 
import sys

#先開啟1.txt檔案,讀取文字內容,然後建立一個匹配函式並呼叫(獲取文字的address)
#終端輸入python3 本檔名.py 匹配內容(例:BATA100)
#匹配具體內容
def reg(data,port):
    pattern = r'^\S+'
    re_obj = re.compile(pattern)
    try:
        head_word = re_obj.match(data).group()
    except Exception:
        return None
    if port == head_word:
        pattern = r'address is (\w{4}\.\w{4}\.\w{4})'
        try:
            match_obj = re.search(pattern,data)
            return match_obj.group(1)
        except Exception:
            return None
    else:
        return None



def main(port):
    fd = open('1.txt','r')
    fd.readline()
    fd.readline()

    while True:
        data = ''
        while True:
            s = fd.readline()
            if s == '\n':
                break 
            if s == '':
                print("search over")
                return
            data += s 
        # 將每段資料傳入函式進行匹配
        result = reg(data,port)
        if result:
            print("address is :",result)
            return 
 
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("argv error")
        sys.exit(1)
    main(sys.argv[1])