Python 正则匹配括号中的任意字符

匹配 [] 任意字符

# 将正则表达式编译成Pattern对象
        pattern = re.compile(r'[[](.*)[]]', re.S)
        # 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None
        match = pattern.match(“[hello],haha")
        if match:
            # 使用Match获得分组信息
            print(match.group())

匹配 () 中的任意字符

# -*- coding:utf-8 -*-

#! python2
import re
string = 'abe(ac)ad)'
p1 = re.compile(r'[(](.*?)[)]', re.S) #最小匹配
p2 = re.compile(r'[(](.*)[)]', re.S)  #贪婪匹配
print(re.findall(p1, string))
print(re.findall(p2, string))

输出:

[‘ac’]
[‘ac)ad’]

  
    展开阅读全文