【问题标题】:How to find characters not in parentheses如何查找不在括号中的字符
【发布时间】:2018-01-01 03:37:54
【问题描述】:

尝试查找所有出现的字符

string1 = '%(example_1).40s-%(example-2)_-%(example3)s_'

这样输出中所有出现的 '-' '_' 不在括号中

['-', '_', '-', '_']

不需要关心嵌套括号

【问题讨论】:

标签: python regex


【解决方案1】:

您可以使用模块re 通过将正则表达式传递给它来做到这一点

import re

str = '%(example_1).40s-%(example-2)_-%(example3)s_'
#remove all occurences of paratheses and what is inside
tmpStr = re.sub('\(([^\)]+)\)', '', str)

#take out other element except your caracters
tmpStr = re.sub('[^_-]', '', tmpStr)

#and transform it to list
result_list = list(tmpStr)

结果

['-', '_', '-', '_']

就像 Bharath shetty 在评论中提到的那样,不要使用 str,它是 python 中内置字符串的保留字

【讨论】:

    【解决方案2】:

    以下将为您提供输出。:

    >>> import re
    >>> str = '%(example_1).40s-%(example-2)_-%(example3)s_'
    >>> print list("".join(re.findall("[-_]+(?![^(]*\))", str)))
    ['-', '_', '-', '_']
    

    它的作用是在str 中而不是在括号中查找包含'-' 和/或'_' 的所有子字符串。由于这些是子字符串,我们通过加入并拆分成一个列表来获得所有这些匹配的字符。

    【讨论】:

    • 太棒了。你能解释一下[^(]*\)) 在做什么吗?
    • 这正是我想要的,谢谢。 @pylang [^(]*)) 匹配括号内的所有字符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 2023-02-16
    • 2023-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多