Python-正则表达式多次匹配要点
要查所有匹配项,⽤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"
运⾏结果:
python正则表达式不包含OK ['2015', '03', '20']
⽰例-查年⽉⽇
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中查⽂件修改记录。
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

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。