【问题标题】:Using Regex to remove brackets and contents if the contents contain any non digits如果内容包含任何非数字,则使用正则表达式删除括号和内容
【发布时间】:2022-01-28 06:59:40
【问题描述】:

如果 [] 中至少有一个非数字,我想删除 [] 和内容。

输入:Tag1[aA], Tag2[55].AA[*], Tag3[A1];

输出:Tag1, Tag2[55].AA, Tag3;

我已经尝试过以下方法,但它只适用于括号内的完全匹配。

import re

line = "'Tag1[aA], Tag2[55].AA[*], Tag3[A1];"

# removes the [] if contents contain non digits only
pattern = r'\[\D+\]'
s = re.sub(pattern, '', line)
print(s)

> "'Tag1, Tag2[55].AA, Tag3[A1];"

【问题讨论】:

    标签: python regex brackets


    【解决方案1】:

    你可以使用:

    \[[^][]*[^][\d][^][]*]
    

    模式匹配:

    • \[匹配[
    • [^][\d]* 可以选择匹配除[] 之外的任何字符
    • [^][\d] 匹配除[ ] 或数字以外的单个字符
    • [^][\d]* 可以选择匹配除[] 之外的任何字符
    • ]匹配]

    Regex demo

    import re
    
    print(re.sub(r"\[[^][]*[^][\d][^][]*]", "", "Tag1[aA], Tag2[55].AA[*], Tag3[A1];"))
    

    输出

    Tag1, Tag2[55].AA, Tag3;
    

    【讨论】:

      【解决方案2】:
      import re
      
      line = "'Tag1[aA], Tag2[55].AA[*], Tag3[A1];"
      re.sub(r'\[[a-zA-Z*]{1,}[\d]{0,}\]', r'', line)
      

      【讨论】:

        【解决方案3】:

        使用此代码,我也考虑了一些其他情况。

        import re
        
        line = "'Tag1[aA], Tag2[55].AA[*], Tag3[A1],Tag4[34],Tag5[1B];"
        
        # removes the [] if contents contain non digits only
        pattern = r'(\[\D.+?\]?|\[.\D.+?\]?)'
        s = re.sub(pattern, '', line)
        print(s)
        

        输出: 'Tag1, Tag2[55].AA, Tag3,Tag4[34],Tag5;

        【讨论】:

          猜你喜欢
          • 2023-02-11
          • 1970-01-01
          • 1970-01-01
          • 2011-01-22
          • 2012-01-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-15
          相关资源
          最近更新 更多