【问题标题】:Please advise on the Python regular expression请就Python正则表达式提出建议
【发布时间】:2020-03-19 06:52:23
【问题描述】:
message = <@U0104FGR7SL> test111 <@U0106LSJ> test33

上面有字符串。

基于模式对应的参考字母

我想拆分文本。

我想把它剪成一个图案。

regex = re.compile("<@U[^>]+>")

match = regex.split (message)

如果我这样做,我会得到一个“test, test22”

<@U0104FGR7SL> test111 
<@U0106LSJ> test33

我想这样拆分。

请告诉我该怎么做。

【问题讨论】:

    标签: python regex split


    【解决方案1】:

    您可以执行以下操作:

    import re
    message = "<@U0104FGR7SL> test111 <@U0106LSJ> test33"
    matches = re.findall("<\S+>\s\S+", message)
    for x in matches:
        print(x)
    # <@U0104FGR7SL> test111
    # <@U0106LSJ> test33
    

    【讨论】:

    • 哇谢谢~!!
    • @김동원 没问题,如果我的回答对你有帮助,可以标记为正确:)
    • @김동원 如果您的字符串在&lt;@U...&gt; 子字符串之后可能包含多个单词,则应该考虑使用更通用的解决方案。看看我的和 Jan 的。
    【解决方案2】:

    另一个 - 使用更新的 regex 模块,它支持按环视分割:

    import regex as re
    
    string = "<@U0104FGR7SL> test111 <@U0106LSJ> test33"
    parts = re.split(r'(?<!\A)(?=<@)', string)
    print(parts)
    

    这会产生

    ['<@U0104FGR7SL> test111 ', '<@U0106LSJ> test33']
    

    a demo on regex101.com

    【讨论】:

      【解决方案3】:

      您可以使用两种re.split 解决方案中的任何一种:

      re.split(r'\s+(?=<@U[^>]+>)', message)    # Any Python version, if matches are whitespace separated
      [x.strip() for x in re.split(r'(?=<@U[^>]+>)', message) if x] # Starting with Python 3.7
      

      注意:在 Python 3.7 中,re.split 最终被修复为使用空匹配进行拆分。

      详情

      • \s+ - 1+ 个空格
      • (?=&lt;@U[^&gt;]+&gt;) - 正向前瞻,需要&lt;@U、除&gt; 之外的1+ 个字符,然后在当前位置右侧紧邻&gt;

      Python demo

      import re
      message = '<@U0104FGR7SL> test111 <@U0106LSJ> test33'
      print ( re.split(r'\s+(?=<@U[^>]+>)', message) )
      # => '<@U0104FGR7SL> test111', '<@U0106LSJ> test33']
      print ( [x.strip() for x in re.split(r'(?=<@U[^>]+>)', message) if x] )
      # => '<@U0104FGR7SL> test111', '<@U0106LSJ> test33']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多