Python中提取指定字符串 取出中间文本 正则表达式

Python中提取指定字符串,从一个字符串中提取<>里面的内容,整理了两种实现方式,后续有更多的实现方式继续更新 
代码如下:

#coding:utf8
import re
import sys
reload(sys)
sys.setdefaultencoding('utf8')
#!/usr/bin/python
template = "我要<歌手名>的<歌曲名>"

def subString1(template):
    copy = False
    finished = False
    slotList = []
    str = ""
    for s in template:
        if s=='<':
            copy = True
        elif s=='>':
            copy = False
            finished = True
        elif copy:
            str = str+s
        if finished:
            slotList.append(str)
            str = ""
            finished = False
    return slotList

def subString2(template):
    rule = r'<(.*?)>'
    slotList = re.findall(rule, template)
    return slotList


slotList = subString1(template)
for slot in slotList:
    print slot

slotList = subString2(template)
for slot in slotList:
    print slot

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/81411601
今日推荐