前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >re正则表格式

re正则表格式

作者头像
用户1733462
发布2018-06-01 17:26:53
6040
发布2018-06-01 17:26:53
举报
文章被收录于专栏:数据处理数据处理
# coding=utf-8
# "正则表达式学习"
import re

# "match方法的工作方式是只有当被搜索字符串的开头匹配模式的时候它才能找到匹配对象"
match = re.match(r'dog', 'dogsdf cat dog')
print match.group()

# "开头没有匹配cat,将返回None"
match = re.match(r'cat', 'dog cat dog')
print match

# "使用re.search查找匹配任意位置,search方法不会限制只从字符串开头匹配,因此可以在中间查找cat"

search = re.search(r'cat', 'dog catsd dog')
print search.group(0)
# "search查找到一个匹配后不会继续查找"
search = re.search(r'dog', 'dog catsd dog')
print search.group(0)

# "使用re.findall-所以匹配对象"
findall = re.findall(r'dog', 'dogsdfs catsd dog')
print findall

# "使用match.start和match.end方法"

match = re.match(r'dog', 'dogsdf cat dog')
print match.start(), match.end()

# "使用match.group通过数字分组"
contactInfo = 'Doe, John: 555-1212'

search = re.search(r'\w+, \w+: \S+', contactInfo)
print search.start(), search.end()
print search.group(0)
search = re.search(r'(\w+), (\w+): (\S+)', contactInfo)
print search.start(), search.end()
print search.group(1)
print search.group(2)
print search.group(3)

# "通过别名访问分组内容"
search = re.search(r'(?P<last>\w+), (?P<first>\w+): (?P<phone>\S+)', contactInfo)
print search.group('last')
print search.group('first')
print search.group('phone')

findall = re.findall(r'(\w+), (\w+): (\S+)', contactInfo)
print findall

html = 'Hello <a href="http://pypix.com" title="pypix">Pypix</a>'\
        'Hello <a href="http://example.com" title"example">Example</a>'

# .*是贪婪模式,将尽可能匹配多的字符
findall = re.findall(r'(<a.*</a>)', html)
print findall
# .*?是非贪婪模式
findall = re.findall(r'(<a.*?</a>)', html)
print findall

# "前向定界符和后向定界符"
strings = ["hello foo", "hello foobar"]
for string in strings:
    # (?=bar)表示匹配bar
    pattern = re.search(r'foo(?=bar)', string)
    if pattern:
        print 'True'
        print pattern.group()
    else:
        print 'False'
strings = ["1hello foo", "2hello foobar", "3hello foobaz"]

for string in strings:
    # (?!bar)表示不匹配bar,如"3hello foobaz"
    pattern = re.search(r'foo(?!bar)', string)
    if pattern:
        print 'True'
        print pattern.group()
    else:
        print 'False'
# "后向界定符类似,但是它查看当前匹配的前面的模式。你可以使用 (?> 来表示肯定界定,(?<! 表示否定界定。"

print '***********************************************'
strings = [  "hello1 bar",         # returns True
             "hello2 foobar",      # returns False
             "hello3 bazbar"]      # returns True
for string in strings:
    pattern = re.search(r'(?=foo)bar', string)
    if pattern:
        pattern.group()
    else:
        print 'False'

# 条件(IF-Then-Else)模式 (?(?=regex)then|else)
print '*******************************************'
strings = [  "<pypix>",    # returns true
             "<foo",       # returns false
             "bar>",       # returns false
             "hello" ]     # returns true
 
for string in strings:
    # ^表示从开始地方匹配,$匹配到结尾, (<)?表示<出现一次或不出现, 
    # 1表示分组(<),当然也可以为空因为后面跟着一个问号。当且仅当条件成立时它才匹配关闭的尖括号
    pattern = re.search(r'^(<)?[a-z]+(?(1)>)$', string)
    if pattern:
        print 'True'
    else:
        print 'False'

# 无捕获组
print '*****************************************'
string = 'hello foobar'
pattern = re.search(r'(f.*)(b.*)', string)
print pattern.group()
print pattern.group(1)
print pattern.group(2)
pattern = re.search(r'(h.*)(f.*)(b.*)', string)
print pattern.group()
print pattern.group(1)
print pattern.group(2)
print pattern.group(3)

pattern = re.search(r'(?:h.*)(f.*)(b.*)', string)
print pattern.group()
print pattern.group(1)
print pattern.group(2)

print '*****************************************'
pattern = re.search(r'(h.*)(?P<fstar>f.*)(?P<bstar>b.*)', string)
print pattern.group('fstar')
print pattern.group('bstar')

# 使用回调函数
template = "Hello [first_name] [last_name], \
Thank you for purchasing [product_name] from [store_name]. \
The total cost of your purchase was [product_price] plus [ship_price] for shipping. \
You can expect your product to arrive in [ship_days_min] to [ship_days_max] business days. \
Sincerely, \
[store_manager_name]"          
# assume dic has all the replacement data          
# such as dic['first_name'] dic['product_price'] etc...          
dic = {          
 "first_name" : "John",          
 "last_name" : "Doe",          
 "product_name" : "iphone",          
 "store_name" : "Walkers",          
 "product_price": "$500",          
 "ship_price": "$10",          
 "ship_days_min": "1",          
 "ship_days_max": "5",          
 "store_manager_name": "DoeJohn"          
}          
result = re.compile(r'(.*)')          
print result.sub('John', template, count=1)

print '*************************************'

# assume dic has all the replacement data          
# such as dic['first_name'] dic['product_price'] etc...          
def multiple_replace(dic, text):
    mapRe = map(lambda key : re.escape("["+key+"]"), dic.keys())
    print mapRe
    pattern = "|".join(mapRe)
    return re.sub(pattern, lambda m: dic[m.group()[1:-1]], text)     
print multiple_replace(dic, template)


for key in dic.keys():
    pattern = re.escape("["+key+"]")
    print pattern
print '***************************'
inputStr = "hello crifan, nihao crifan";
replacedStr = re.sub(r"hello (?P<name>\w+), nihao (?P=name)", "\g<name>", inputStr);
print "replacedStr=",replacedStr; #crifan

print '***************************'
inputStr = "hello crifan, nihao crifan";
replacedStr = re.sub(r'crifan', "crifanli", inputStr);
print "replacedStr=",replacedStr; #crifanli

def pythonReSubDemo():
    """
        demo Pyton re.sub
    """
    inputStr = "hello 123 world 456";
     
    def _add111(matched):
        intStr = matched.group("number"); #123
        intValue = int(intStr);
        addedValue = intValue + 111; #234
        addedValueStr = str(addedValue);
        return addedValueStr;
         
    replacedStr = re.sub("(?P<number>\d+)", _add111, inputStr);
    print "replacedStr=",replacedStr; #hello 234 world 567
pythonReSubDemo()

inputStr = "hello 123 world 456";
search = re.findall('(?P<number>\d+)', inputStr)
print search
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.08.02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档