【问题标题】:python return matching and non-matching patterns of stringpython返回字符串的匹配和不匹配模式
【发布时间】:2014-06-27 17:04:30
【问题描述】:

我想将字符串拆分为匹配正则表达式模式的部分和不匹配的部分到列表中。

例如

import re
string = 'my_file_10'
pattern = r'\d+$'
#  I know the matching pattern can be obtained with :
m = re.search(pattern, string).group()
print m
'10'
#  The final result should be as following
['my_file_', '10']

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    您可以使用re.split 列出这些单独的匹配项并使用filter,它会过滤掉所有被认为是错误的元素(空字符串

    >>> import re
    >>> filter(None, re.split(r'(\d+$)', 'my_file_015_01'))
    ['my_file_015_', '01']
    

    【讨论】:

    • 好主意,但我需要一些只包含两个部分的东西。例如,如果字符串是 'my_file_015_01',您的解决方案将给出 ['my_file_', '015', '_', '01']。这使我的代码中的事情变得复杂。 Martijn 的回答更适合。
    • @user1850133 更新答案
    【解决方案2】:

    在模式周围加上括号使其成为捕获组,然后使用re.split() 生成匹配和不匹配元素的列表:

    pattern = r'(\d+$)'
    re.split(pattern, string)
    

    演示:

    >>> import re
    >>> string = 'my_file_10'
    >>> pattern = r'(\d+$)'
    >>> re.split(pattern, string)
    ['my_file_', '10', '']
    

    因为您在字符串末尾拆分数字,所以包含一个空字符串。

    如果你只期望 one 匹配,在字符串的末尾(你的模式中的 $ 强制在这里),那么只需使用 m.start() 方法来获取索引切片输入字符串:

    pattern = r'\d+$'
    match = re.search(pattern, string)
    not_matched, matched = string[:match.start()], match.group()
    

    这会返回:

    >>> pattern = r'\d+$'
    >>> match = re.search(pattern, string)
    >>> string[:match.start()], match.group()
    ('my_file_', '10')
    

    【讨论】:

    • 这肯定回答了最初的问题。现在,我想知道在结果列表中找出匹配的 哪些 元素和哪些不匹配的pythonic 方法是什么。我需要它,并且匹配每个元素以进行检查感觉有点笨拙。
    猜你喜欢
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 2021-12-06
    • 2013-07-11
    • 2014-05-07
    • 1970-01-01
    相关资源
    最近更新 更多