【问题标题】:Split string with optional substring使用可选子字符串拆分字符串
【发布时间】:2019-06-11 18:19:57
【问题描述】:

这里_also是可选的,如何拆分字符串使_also成为可选?

>>> aa="may_be_this.is_the_string"
>>> aa.split('this.')[1]
'is_the_string'
>>>
>>> aa="may_be_this_also.is_the_string"
>>> aa.split('this[_also]*.')[1] # something like this, to make _also as optional substring.

【问题讨论】:

  • "may_be_this_also_also.is_the_string" 会如何运作? (两个 _also's)
  • 'this[_also]*.' 将从'textlike_this_____aaaalllssooooooJuhu' 拆分为['text','uhu'] - 这应该会发生吗?
  • "may_be_this_also.is_the_string" 的预期输出是什么?
  • @DeveshKumarSingh, is_the_string
  • 好的,评论者指出的其他输出呢?比如"may_be_this_also_also.is_the_string"'textlike_this_____aaaalllssooooooJuhu'

标签: python regex python-3.x python-3.6


【解决方案1】:

像这样的通用拆分正则表达式

this(?:_also)*\.

其中有一个必需的this
其次是许多可选的_also
后跟一个文字点.

没有捕获任何内容,因此该信息作为元素被排除在外。

【讨论】:

    【解决方案2】:

    你在看re.split

    In [21]: import re                                                                                    
    
    In [22]: aa="may_be_this_also.is_the_string"                                                          
    
    In [23]: re.split('this(_also)+.', aa)                                                                
    Out[23]: ['may_be_', 'is_the_string']
    
    In [24]: aa="may_be_this.is_the_string"                                                               
    
    In [25]: re.split('this.', aa)                                                                        
    Out[25]: ['may_be_', 'is_the_string']
    

    【讨论】:

      【解决方案3】:

      您可以使用正则表达式进行拆分:

      你应该在你的模式中屏蔽文字 '.' - 否则 '.' 代表任何东西。如果您使用?(== 0 或 1 次出现)将其归因于它,则可以使用非分组 (?:....) 添加可选模式:

      import re
      
      aa = "may_be_this.is_the_string"
      print(re.split(r'this\.',aa))           # 'this' and literal '.'
      
      bb = "may_be_this_also.is_the_string"
      print(re.split(r'this(?:_also)?\.',bb)) # 'this' and optional '_also' and literal '.'
      

      输出:

      ['may_be_', 'is_the_string']
      ['may_be_', 'is_the_string']
      

      使用 '[_also]*' 允许 [...] 内的所有字符出现 0..n 次 - 可能不是您想要的。

      使用原始字符串是获取指定正则表达式模式的好习惯。

      您可能想阅读regex-info - 它很多,但涵盖了基础知识。要测试正则表达式,我也想支持 http://www.regex101.com 你 - 它有 python 方言并以明文解释正则表达式。

      【讨论】:

        猜你喜欢
        • 2015-12-28
        • 1970-01-01
        • 2013-05-21
        • 2016-04-28
        • 2019-10-11
        • 2018-09-07
        • 2015-12-18
        • 2011-11-25
        相关资源
        最近更新 更多