python正则表达式re模块
首先,介绍下正则表达式,举个例子:
r"(?<=<h1>).+?(?=</h1>)"
?<=前向匹配,匹配目标字符串之前的内容(向前匹配但不取用)
?=后向匹配,其他参考上一句
?非贪婪匹配,即匹配到第一符合的
不加?为贪婪匹配,会尽可能多的匹配
1 import re 2 key = '''{"IsSuccess":true,"Content":"[{\"BusinessID\":9403977,\"MerchantNo\":\"802440353110762\",\"DueAmt\":0.00,\"NextBillAmt\":1300.00,\"TotalAmt\":1300.00,\"DueProcedu 3 resAmout\":0.0,\"LastBillIndex\":7,\"NextBillMonth\":\"2020/04\",\"LoanKind\":\"LOANKIND/KAKADAI\",\"IsNeedEnoughPayBill\":false,\"SeparatePayFlag\":0,\"SPayAmt\":0.0,\"SDeductAmt\":0.0}]"} 4 ''' 5 p1 = r"\.0+(?=[^0])" # 这是我们写的正则表达式规则 6 pattern1 = re.compile(p1) # 我们在编译这段正则表达式 7 print(pattern1.findall(key)) # 查看下匹配到什么 8 9 newKey = re.sub(p1, "", key) 10 print("原文本:" + key) 11 print("新文本:"+newKey)
另外还有re.search等方法
正则表达式上说:
. 匹配除换行符以外的任意字符
\d 匹配数字
\b 匹配单词的开始或结束
^ 匹配字符串的开始
$ 匹配字符串的结束
\w 匹配字母或数字或下划线或汉字 等价于 '[^A-Za-z0-9_]'。
\w 能不能匹配汉字要视你的操作系统和你的应用环境而定
\s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。(待考证)
例2:
import re line = 'SELECT ToAccount,billid,DeductItem,DeductAmt,SendResult,ResultDesc,BusinessID,AccountNo,ReceivedType,ReceivedTime FROM deduct.DeductInstruction WHERE BusinessID=@bid ORDER BY ReceivedTime desc' pattern = re.compile(r'(?<=\s)[^\s]+(?=\sWHERE)') table_name = pattern.findall(line) print(table_name) #结果为 pay.DeductInstruction #正则中 \s 匹配空格
参考:https://blog.csdn.net/wjs30078111/article/details/85108621