Regex in Python

Core module

import re

General Syntax
  • .
  • []
    a set of chars, common cases as follows:
    (1)chars list
    (2)chars range
    (3)special chars lose special meanings, like “[(+)]” will match “(” , “+” and “)”
    (4)not within chars range, like “[^5]” match any chars except “5”
  • ()
  • ?
    zero or one repetion of 前面一个RE或字符。
    Like “ab?” it indicates either “a” or “ab”

  • +
    one or more repetions of 前面一个RE或字符。
    Like“ab+”, it indcates “a” can be followed by non-zero number of “b”.

  • *
    zero or more repetions of 前面一个RE或字符。
    Like “ab*” , it indicates “a” can be followed by any number of “b”.

  • *? , +? , ??
    add ? after * , + , ? will execute in non-greedy or minimal fashion
    Like “<.*?>” only match “<\a>” in “<\a>b<\c>”.(Note: “\” is an escaping character)

  • \s
    match any whitesapce chars as “[ \t\r\n\f\v]” if UNICODE flag not specified.

Key Methods
  • match : used for str match
  • search : used for str search
  • sub : used for str search and replace

这部分的关键点在于对于具体的应用需求,构建regex pattern.

Application Case and experience

(1)specific tag search in xml and update its value

在匹配时,单个\s字符就可以匹配所有连续空格;

Note:多行匹配;方法中编译标识的掌握与灵活运用,如flags=re.S使得 “.”匹配任意字符包括新行(\n).

(2)similar str style match verification

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值