V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
fortunezhang
V2EX  ›  Python

python 正则找到规律数据

  •  1
     
  •   fortunezhang · 2014-11-14 11:47:22 +08:00 · 3604 次点击
    这是一个创建于 3422 天前的主题,其中的信息可能已经有所发展或是发生改变。
    字符串: <Data>1=1&2=2</Data><Data>abc</Data><Data>nihao</Data>
    我想找到得到的是['1=1&2=2','abc','nihao']
    请各位帮忙解答一下,本人python菜鸟,勿喷,谢谢。
    6 条回复    2014-11-15 00:09:55 +08:00
    c
        1
    c  
       2014-11-14 11:54:00 +08:00   ❤️ 1
    re.findall('<Data>([^<]+)</Data>', s)
    Kai
        2
    Kai  
    MOD
       2014-11-14 12:19:56 +08:00 via iPhone   ❤️ 1
    移动到 /go/python
    ChanneW
        3
    ChanneW  
       2014-11-14 12:43:25 +08:00
    def tsplit(string, delimiters):
    """Behaves str.split but supports multiple delimiters."""

    delimiters = tuple(delimiters)
    stack = [string,]

    for delimiter in delimiters:
    for i, substring in enumerate(stack):
    substack = substring.split(delimiter)
    stack.pop(i)
    for j, _substring in enumerate(substack):
    stack.insert(i+j, _substring)

    return stack

    s ="<Data>1=1&2=2</Data><Data>abc</Data><Data>nihao</Data>"
    tsplit(s, (',', '<Data>', '</Data>'))
    uJohnny
        4
    uJohnny  
       2014-11-14 15:45:15 +08:00
    如果只是标签里的数据, 用lxml吧.
    不想用的话, 就参考下这个: http://bit.ly/1qHjIeV
    fortunezhang
        5
    fortunezhang  
    OP
       2014-11-14 17:46:23 +08:00
    @Kai 不知道怎么移动了。下次注意。thx
    irosyking
        6
    irosyking  
       2014-11-15 00:09:55 +08:00
    正则表达式为 (?<=<data>)(.*?)(?=<\/data>)

    import re

    m=re.findall(r'(?<=<data>)(.*?)(?=<\/data>)','<Data>1=1&2=2</Data><Data>abc</Data><Data>nihao</Data>',re.I|re.M)

    print m
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3146 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 12:32 · PVG 20:32 · LAX 05:32 · JFK 08:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.