推荐学习书目
› 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
ashes1122
V2EX  ›  Python

求一个 Python 正则表达式

  •  
  •   ashes1122 · May 20, 2020 · 4051 views
    This topic created in 2360 days ago, the information mentioned may be changed or developed.

    工作上需要写个 python 脚本,取出一串字符种第五个,前面的字符,迫于现学的 python,实在写不出来了,求 v 友帮写一下,谢谢 v 友们了。

    字符串如下:
    

    A1234, A1457, A1516, A1518, A1528, A1529, A1530, A1533, iPhone 5s, ME341LL/A, ME342LL/A, ME344LL/A, ME345LL/A, ME347LL/A, ME348LL/A, ME349LL/A, ME432LP/A

    15 replies  •  2020-05-25 19:19:21 +08:00
    ranleng
    ranleng
    May 20, 2020❤️1
    1
    直接 split 然后 [:5] 再 join 一下?
    jdhao
    jdhao
    May 20, 2020 via Android❤️1
    2
    😂
    lonelinsky
    lonelinsky
    May 20, 2020❤️1
    3
    import re
    groups = re.match('^(([^,]*,){5})', s).groups()
    result = groups[0][:-1] if groups else None
    cnmllll
    cnmllll
    May 20, 2020❤️1
    4
    l = s.split(",")
    之后想怎么处理都行了
    ashes1122
    ashes1122
    OP
    May 20, 2020
    5
    好的,谢谢各位。
    @ranleng
    @jdhao
    @lonelinsky
    @cnmllll
    HashV2
    HashV2
    May 20, 2020
    6
    result = ",".join(s.split(",")[:5])
    为啥非要正则,有硬性要求吗?
    ashes1122
    ashes1122
    OP
    May 20, 2020
    7
    @HashV2 现学,其他的更不知道咋搞。
    resist
    resist
    May 20, 2020
    8
    你这个需求太简单了,建议直接操作字符串,如果是自己玩玩,别人用不着,那就可以使用正则
    HashV2
    HashV2
    May 20, 2020
    9
    @ashes1122 可以 我是工作一年多了 《流畅的 python 》一定要看
    还有标准库 https://docs.python.org/zh-cn/3/library/index.html
    加油~~
    L00kback
    L00kback
    May 20, 2020
    10
    @HashV2 老哥,你这是取了前 6 个内容,不对啊,应该是 result=s.split(",")[4].strip()
    L00kback
    L00kback
    May 20, 2020
    11
    需求说的不太清楚,如果是开头到第五个逗号之间的字符串就是 result = ",".join(s.split(",")[:4])
    lonelinsky
    lonelinsky
    May 20, 2020
    12
    @L00kback 你重新数下看看? Python 的 slice 是前闭后开的。


    这个问题还有一个点是如何处理 ",“ 数量小于 5 的情况。另外从性能的角度来考虑 split + join 的方法应该是优于 正则 的。
    Telegram
    Telegram
    May 20, 2020
    13
    同意一楼,能 split 的尽量用这个
    ericls
    ericls
    May 21, 2020 via iPhone
    14
    Regex the problem for all your solutions
    soraping
    soraping
    May 25, 2020
    15
    reg_str = '.*?(\w{5}).*?'

    list_str = re.findall(reg_str, str11)

    print(list_str)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3027 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 11:43 · PVG 19:43 · LAX 03:43 · JFK 06:43
    ♥ Do have faith in what you're doing.