fnmatch模块
- fnmatch
全称是file name match,文件名匹配。支持unix shell的通配符。
模式 | 含义 |
---|---|
* | 匹配所有 |
? | 匹配所有单个字符 |
-
fnmatch.fnmatch(filename, pattern)函数的使用
匹配filename文件名的pattern模式。使用底层操作系统的大小写敏感模式。 -
示例
匹配当前目录下txt文件夹下的所有*.txt文件名。
from fnmatch import fnmatch
import os
for file in os.listdir('.\\txt'):
if fnmatch(file, '*.txt'):
print("the file name is: ", file)
-
fnmatch.fnmatchcase(filename, pattern)函数的使用
测试filename是否匹配pattern,返回True或False;在实例归一化下比较,且不使用os.path.normcase()。
使用方法完全跟fnmatch()一样。 -
扩展使用
虽然fnmatch是用来匹配文件的,但也可以用来匹配字符串。用作字符串的正则表达式。值得注意的是,在匹配字符串的时候,行尾的回车字符\n 也需要考虑。
#!/usr/bin/python
# -*- coding: utf-8 -*-
from fnmatch import fnmatch as match
import re
#method 1
#with open("C:\\Users\\GXP\\Desktop\\txt\\txt1.txt", "r", encoding = 'UTF-8') as openFile:
with open("C:\\Users\\GXP\\Desktop\\txt\\txt.txt", "r") as openFile:
matchName = [field for field in openFile.readlines() if match(field, "*guo*ping*")]
#print(line.strip()) #equal print(line, end = '')
print(matchName)
compile函数
compile 函数用于编译正则表达式,创建模式对象,供 match()、search() 、findall()等函数使用。
- 实例
将一个字符串通过正则表达式匹配成一个字典对象,然后通过键值对,打印输出需要的内容。
from fnmatch import fnmatch as match
import re
line ='192.168.0.1 25/Oct/2012:14:46:34 "GET /api HTTP/1.1" 200 44 "http://abc.com/search" "Mozilla/5.0"'
#reg = re.compile('^(?P<remote_ip>[^ ]*) (?P<date>[^ ]*) "(?P<request>[^"]*)" (?P<status>[^ ]*) (?P<size>[^ ]*) "(?P<referrer>[^"]*)" "(?P<user_agent>[^"]*)"')
reg = re.compile('(?P<remote_ip>.*) "(?P<request>[^"]*)" (?P<status>[^ ]*) (?P<size>[^ ]*) "(?P<referrer>[^"]*)" "(?P<user_agent>.*)"')
regMatch = reg.match(line)
linebits = regMatch.groupdict()
print(linebits)
print() #print one empty line
for k, v in linebits.items() :
print(k+": "+v)
findall函数
-
使用方式
a = re.findall(“匹配规则”, “要匹配的字符串”) -
实例1
import re
str = "a123b456b"
print(re.findall(r"a(.*)b", str))
- 实例2
先通过compile编译成模式对象,然后在通过findall匹配出需要的结果。
re.compile(’\d’) 这个函数的作用是仅仅匹配数字。
import re
string ='a1b2c3d4e5f6'
pattern = re.compile('\d') # 匹配数字
reg_l = pattern.findall(string)
print(reg_l)