专栏首页数据处理re正则表格式

re正则表格式

# 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

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • kaggle-识别手写数字

    用户1733462
  • __new__,__init__

    用户1733462
  • scikit-learning小试牛刀

    用户1733462
  • python五十七课——正则表达式(边界字符)

    演示匹配锚字符(边界字符) ^:从字符串头部开始匹配,在开启多行模式下(re.M),可以尝试匹配每一行的头部数据 $:从字符串尾部开始匹配,在开启多行模式下(r...

    hankleo
  • Python group()小结

    一开始我理解为group(n)(n=1,2,3)会根据括号里的正则表达式进行匹配,每次都是从字符串a的起始位置开始,会自动匹配到‘123’,‘abc’,‘1...

    py3study
  • Django项目之Elasticsearch搜索引擎

    sudo docker image pull delron/elasticsearch-ik:2.4.6-1.0

    菲宇
  • [PYTHON] 核心编程笔记(16.P

    套接字只有两种一种是面向连接套接字,即在通讯之前一定要建立一条连接,这种通讯方式提供了顺序的,可靠的不会重复的数据传输,每一份要发送的信息都会拆分成多份,每份都...

    py3study
  • Bystack的高TPS共识算法

    共识算法是分布式系统保证节点数据状态一致性的方法,在区块链的共识算法分POW(工作量证明)和POS(权益证明)两大类。第一类POW模式是在公链项目中运用的最广泛...

    比原链Bytom
  • (数据科学学习手札24)逻辑回归分类器原理详解&Python与R实现

    一、简介   逻辑回归(Logistic Regression),与它的名字恰恰相反,它是一个分类器而非回归方法,在一些文献里它也被称为logit回归、最大熵...

    Feffery
  • Bystack的高TPS共识算法

    共识算法是分布式系统保证节点数据状态一致性的方法,在区块链的共识算法分POW(工作量证明)和POS(权益证明)两大类。第一类POW模式是在公链项目中运用的最广泛...

    比原链Bytom

扫码关注云+社区

领取腾讯云代金券