【Python】【正则】

#正则表达式相关符号说明:https://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html

#正则对字符串相关操作:https://www.cnblogs.com/amengduo/p/9586732.html

1、python xpath 正则匹配

匹配当前标签(i对象)中的a标签,满足条件:以http开始并且以allure结束的href标签

说明:

1.1、namespaces={"re": "http://exslt.org/regular-expressions"} 按照这样写上即可

1.2、.//a 标签当前对象下的a标签(这里的当前对象为tr_list列表中的i对象)

1.3、“.+”表示任意多个字符,“^”表示字符串开始位置,“$”表示字符串结束位置

for i in tr_list:
    report_url = i.xpath(
        r'.//a[re:match(@href, "^http.+allure$")]', namespaces={"re": "http://exslt.org/regular-expressions"}
    )

2、python正则工具

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@Time    :2021/9/26 14:29
@Author  :维斯
@File    :RegularTool.py
@Version :1.0
@Function:
"""
import re


class RegularTool:
    @staticmethod
    def space(target: str, is_del_start_end: bool = True, is_print: bool = False):
        """
        空格过滤(多个连续空格 替换为一个空格)
        :param target: 目标字符串
        :param is_del_start_end: 是否删除字符串首尾的空格
        :param is_print: 是否打印
        """
        ''' 1 多个连续空格 替换为1个空格 '''
        if is_print: print(f'前:{target}')  # 前:  dsaj    带回家  交换 机 h       j
        pattern1 = re.compile(' +')  # 匹配1个或多个空格
        new_str1 = re.subn(pattern1, ' ', target)[0]  # 将匹配到的1个或多个空格 替换为1个空格
        if is_print: print(f'后:{new_str1}')  # 后: dsaj 带回家 交换 机 h j

        ''' 2 删除首尾空格 '''
        if is_del_start_end:
            # 删除以空格开始的
            pattern2_s = re.compile('^ +')
            new_str2_s = re.subn(pattern2_s, '', new_str1)[0]
            # 删除以空格结束的
            pattern2_e = re.compile(' +$')
            new_str2_e = re.subn(pattern2_e, '', new_str2_s)[0]
            if is_print: print(f'删:{new_str2_e}')  # 删:dsaj 带回家 交换 机 h j
            return new_str2_e
        return new_str1


if __name__ == '__main__':
    target_str = '  dsaj    带回家  交换 机 h       j    '
    RegularTool.space(target_str, is_print=True)
前:  dsaj    带回家  交换 机 h       j    
后: dsaj 带回家 交换 机 h j 
删:dsaj 带回家 交换 机 h j
如果忍耐算是坚强 我选择抵抗 如果妥协算是努力 我选择争取
原文地址:https://www.cnblogs.com/danhuai/p/15356525.html