【问题标题】:how to remove parantheses and string from a string [duplicate]如何从字符串中删除括号和字符串[重复]
【发布时间】:2020-02-21 05:21:26
【问题描述】:

从字面上看,我一直在尝试解决这个问题的方法,但似乎我对正则表达式很差;)

我需要从列表中的字符串中删除 (WindowsPath 和 )"

     x= ["(WindowsPath('D:/test/1_birds_bp.png'),WindowsPath('D:/test/1_eagle_mp.png'))", "(WindowsPath('D:/test/2_reptiles_bp.png'),WindowsPath('D:/test/2_crocodile_mp.png'))"]

所以我尝试了

 import re
 cleaned_x = [re.sub("(?<=WindowsPath\(').*?(?='\))",'',a) for a in x]

输出

["(WindowsPath(''),WindowsPath(''))", "(WindowsPath(''),WindowsPath(''))"]

我需要的是;

cleaned_x= [('D:/test/1_birds_bp.png','D:/test/1_eagle_mp.png'), ('D:/test/2_reptiles_bp.png','D:/test/2_crocodile_mp.png')]

基本上是列表中的元组。

【问题讨论】:

  • 每个字符串都以( WindowsPath (...))开头的时候为什么要使用re 使用切片不是很容易吗?
  • 只是好奇-如果您只想删除它们(并且它们是您想要删除的固定子字符串),是否需要使用正则表达式?你不能使用标准的字符串替换()函数吗?
  • @Richard 任何能给出预期结果的东西都对我有用;)
  • ...其实我又看了一遍,我认为你确实需要使用正则表达式。 ...稍等片刻:D
  • @Richard 你们是很好的帮助!感谢您的时间和努力!这是一个很棒的社区!

标签: python regex python-3.x string split


【解决方案1】:

您可以像这样使用re.findall 来完成此操作:

>>> cleaned_x = [tuple(re.findall(r"[A-Z]:/[^']+", a)) for a in x]
>>> cleaned_x
[('D:/test/1_birds_bp.png', 'D:/test/1_eagle_mp.png'), ('D:/test/2_reptiles_bp.png', 
'D:/test/2_crocodile_mp.png')]
>>> 

希望对你有帮助。

【讨论】:

    【解决方案2】:

    也许您可以使用捕获组?例如:

    import re
    
    re_winpath = re.compile(r'^\(WindowsPath\(\'(.*)\'\)\,WindowsPath\(\'(.*)\'\)\)$')
    
    def extract_pair(s):
        m = re_winpath.match(s)
        if m is None:
            raise ValueError(f"cannot extract pair from string: {s}")
        return m.groups()
    
    pairs = list(map(extract_pair, x))
    

    【讨论】:

    • 非常感谢!真的很喜欢流量!
    【解决方案3】:

    这是我的看法,

    不漂亮,我分两步完成,以免制作正则表达式意大利面,如果你愿意,你可以将它变成一个列表理解,但它应该可以工作

    for a in x:
        a = re.sub('(\()?WindowsPath', '', a)
        a = re.sub('\)$','', a)
        print(a)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-12
      • 2021-01-29
      • 1970-01-01
      • 2020-06-05
      • 2012-03-16
      • 2018-08-16
      • 1970-01-01
      相关资源
      最近更新 更多