要点
要查找所有匹配项,用findall函数。
findall帮助信息
pydoc re
findall Find all occurrences of a pattern in a string.
findall(pattern, string, flags=0)
Return a list of all non-overlapping matches in the string.
If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result.
示例一
找所有的数字。
#!/usr/bin/env python
import re
result = re.findall("(\d+)", "2015-03-20")
if result:
print "OK",
print result
else:
print "FAIL"
运行结果:
OK ['2015', '03', '20']
示例-查找年月日
#!/usr/bin/env python
import re
def debug_matches(result):
count = len(result)
if count == 0:
print "No match item."
return
for item in result:
year, month, day = item
print "year:", year, ", month:", month, ", day:", day
result = re.findall("(\d+)-(\d+)-(\d+)", "First 2015-03-20, Second 2016-04-21, ...")
if result:
print "OK",
print result
debug_matches(result)
else:
print "FAIL"
运行结果:
OK [('2015', '03', '20'), ('2016', '04', '21')]
year: 2015 , month: 03 , day: 20
year: 2016 , month: 04 , day: 21
示例三-git log分析
git log中查找文件修改记录。
#!/usr/bin/env python
import re
def debug_matches(result):
count = len(result)
if count == 0:
print "No match item."
return
for item in result:
first_filename, second_filename, start_line, line_number = item
print "first file:", first_filename,
print ", second file:", second_filename,
print ", start line:", start_line,
print ", line number:", line_number
git_log = '''
index 98d2cfb..50d2a32 100644
--- a/arch/arm/boot/dts/qcom/filename1.dtsi
--- b/arch/arm/boot/dts/qcom/filename1.dtsi
@@ -419,6 +419,12 @@
qcom,warm-bat-decidegc = <450>;
qcom,cool-bat-decidegc = <100>;
qcom,warm-bat-decidegc = <0>;
+ xyz,batt-cold-percentage = <80>;
+ xyz,batt-hot-percentage = <25>;
diff --git a/drivers/hwmon/filename2.c b/drivers/hwmon/filename2.c
index fba252e..9179239 100644
--- a/drivers/hwmon/filename2.c
--- b/drivers/hwmon/filename2.c
@@ -419,6 +429,22 @@
'''
result = re.findall("--- a([^\n]+)\n--- b([^\n]+)\n@@ -[\d,]+\ \+(\d+),(\d+)\ ", git_log)
if result is not None: # or if result:
print "OK",
print result
debug_matches(result)
else:
print "FAIL"
运行结果:
OK [(‘/arch/arm/boot/dts/qcom/filename1.dtsi’, ‘/arch/arm/boot/dts/qcom/filename1.dtsi’, ‘419’, ‘12’), (‘/drivers/hwmon/filename2.c’, ‘/drivers/hwmon/filename2.c’, ‘429’, ‘22’)]
first file: /arch/arm/boot/dts/qcom/filename1.dtsi , second file: /arch/arm/boot/dts/qcom/filename1.dtsi , start line: 419 , line number: 12
first file: /drivers/hwmon/filename2.c , second file: /drivers/hwmon/filename2.c , start line: 429 , line number: 22