【问题标题】:String splitting in Python using regex使用正则表达式在 Python 中进行字符串拆分
【发布时间】:2012-05-12 09:20:29
【问题描述】:

我正在尝试在 Python 中拆分一个字符串,以便在某个正则表达式之前得到所有内容。

示例字符串:"Some.File.Num10.example.txt"

我需要这部分之前的所有内容:"Num10",正则表达式:r'Num\d\d'(数量会有所不同,可能会发生什么)。

关于如何做到这一点的任何想法?

【问题讨论】:

    标签: python regex


    【解决方案1】:
    >>> import re
    >>> s = "Some.File.Num10.example.txt"
    >>> p = re.compile("Num\d{2}")
    >>> match = p.search(s)
    >>> s[:match.start()]
    'Some.File.'
    

    这会比进行拆分更有效,因为搜索不必扫描整个字符串。它在第一场比赛中中断。在您的示例中,由于字符串很短,因此不会有所不同,但是如果您的字符串很长并且您知道匹配将在开头,那么这种方法会更快。

    我刚刚写了一个小程序来分析 search() 和 split() 并确认了上述断言。

    【讨论】:

    • 你可以简单地使用p = re.compile("Num\d"),因为数字可以是任何东西,所以我们只关心它何时从字符串开始。
    【解决方案2】:
    >>> import re
    >>> text = "Some.File.Num10.example.txt"
    >>> re.split(r'Num\d{2}',text)[0]
    'Some.File.'
    

    【讨论】:

      【解决方案3】:

      你可以使用 Python 的re.split()

      import re
      
      my_str = "This is a string."
      
      re.split("\W+", my_str)
      
      ['This', 'is', 'a', 'string', '']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-06
        • 2013-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多