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
sunhk25
V2EX  ›  Python

Python 正则分割字符串保留分隔符

  •  
  •   sunhk25 · 2019-11-20 20:39:54 +08:00 · 3072 次点击
    这是一个创建于 1590 天前的主题,其中的信息可能已经有所发展或是发生改变。
    • Python 正则分割字符串保留分隔符
    • 分隔符是一个的时候可以,两个以上有什么好办法
        s='123AA456B789AAA'
        # 想分割成:123AA 456B 789AAA
    
    7 条回复    2019-11-21 00:13:42 +08:00
    xpresslink
        1
    xpresslink  
       2019-11-20 20:58:31 +08:00   ❤️ 1
    非要用 split 么?
    >>> s='123AA456B789AAA'
    >>> import re
    >>> re.findall('\d+[AB]+',s)
    ['123AA', '456B', '789AAA']
    sunhk25
        2
    sunhk25  
    OP
       2019-11-20 21:22:52 +08:00 via Android
    @xpresslink 怎么都可以,不过分隔符 AA B AAA 都是不固定的
    ddzzhen
        3
    ddzzhen  
       2019-11-20 21:37:17 +08:00 via Android   ❤️ 1
    分割的依据都没说,你指望得到解决方案?
    sunhk25
        4
    sunhk25  
    OP
       2019-11-20 22:40:08 +08:00 via Android
    @ddzzhen AA B AAA 是指定的分隔符,长度优先
    ksedz
        5
    ksedz  
       2019-11-20 22:46:50 +08:00
    split 的话大概是这样,如果要连起来,像#1 说的 findall 比较好

    ```python
    In [1]: import re

    In [2]: s = '123AA456B789AAA'

    In [3]: re.split(r"[AB]", s)
    Out[3]: ['123', '', '456', '789', '', '', '']

    In [4]: re.split(r"([AB])", s)
    Out[4]: ['123', 'A', '', 'A', '456', 'B', '789', 'A', '', 'A', '', 'A', '']

    In [5]: re.split(r"([AB]+)", s)
    Out[5]: ['123', 'AA', '456', 'B', '789', 'AAA', '']
    ```
    cherbim
        6
    cherbim  
       2019-11-20 23:40:55 +08:00
    要是分隔符只为字母,建议正则
    necomancer
        7
    necomancer  
       2019-11-21 00:13:42 +08:00
    一楼答案没毛病啊
    In [1]: re.findall(r"\d+[A-Z]+", s)
    Out[1]: ['123AA', '456B', '789AAA']
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1014 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 19:38 · PVG 03:38 · LAX 12:38 · JFK 15:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.