十三、正则练习题

正则常用语法

单字符匹配

. 匹配除换行符之外的任意一个字符。
[…] 表示匹配一个字符集集合,如[A-Za-z0-9]表示匹配所有字母和数字。 [^…] 表示匹配除该字符集集合指定字符外的任意字符。如[^0-9]表示匹配除数字之外的所有字符。
\ 转义字符,用来改变特殊字符的原有含义(使其表示本身)。
预定义字符集
\d 表示数字
\D 表示非数字
\s 表示空白字符
\S 表示非空白字符
\w 表示字母和数字
\W 表示非字母和数字
字符次数匹配
* 匹配前一个字符0或者无限次
+ 匹配前一个字符1或者无限次
? 匹配前一个字符0或者1次

边界匹配

^ 匹配字符串开头
$ 匹配字符串结尾

分组

(…) 分组
(?P) 分组,并且指定该分组的名称为NAME。
(?P=NAME) 引用名称为NAME的分组所匹配到的字符串,配合上一个使用

练习题一

import re
import requests

url = "http://qwd.jd.com/fcgi-bin/qwd_searchitem_ex?skuid=26878432382%7C1658610413%7C26222795271%7C25168000024%7C11731514723%7C26348513019%7C20000220615%7C4813030%7C25965247088%7C5327182%7C19588651151%7C1780924%7C15495544751%7C10114188069%7C27036535156%7C10123099847%7C26016197600%7C10503200866%7C16675691362%7C15904713681"

session = requests.session()
r = session.get(url)
html = r.text
# print(html)


reg = re.compile(r"\"skuid\":\"(\d+)\",\s+\"\S+\s+\"skuurl\"\S+\s+\"skuimgurl\":\"(\S+)\",")
result = reg.findall(html)
print(result)
import codecs
import re

import os

regUpstream = re.compile(r"\s*(upstream\s+(\S+)\s+{[^}]+})")

with codecs.open("ga10.wms5.jd.com.txt") as fu:
    textList = regUpstream.findall(fu.read())
    if not os.path.exists("upstream"):
        os.mkdir("upstream")
    os.chdir("upstream")
    for item in textList:
        with codecs.open(item[1], "w") as fw:
            fw.write(item[0])
    os.chdir("..")

练习题二


regLocation = re.compile(r"(location\s+/(\S+)/\s+{\s+proxy_next_upstream.*[^]]*?})")
with codecs.open("ga10.wms5.jd.com.txt") as fl:
    textLocation = regLocation.findall(fl.read())
    if not os.path.exists("location"):
        os.mkdir("location")
    os.chdir("location")
    for each in textLocation:
        file = each[1] + ".locaion.conf"
        with codecs.open(file, "w") as flw:
            flw.write(each[0])

猜你喜欢

转载自blog.csdn.net/weixin_39934221/article/details/80202339