代码之家  ›  专栏  ›  技术社区  ›  KubiK888

复合正则表达式,用于删除python中特殊字符和一组可能的后续字符之间的子字符串

  •  1
  • KubiK888  · 技术社区  · 6 年前

    我想把这些转过来

    (book/livre), (manitoba), the (territories/des territoires), canada
    
    (book/livre), (ontario), the territories/des territoires, canada
    
    book/livre 1, alberta, the territories, canada
    

    (book), (manitoba), the (territories), canada
    
    (book), (ontario), the territories, canada
    
    book 1, alberta, the territories, canada
    

    意思是我想删除/和之间的所有内容,或者,

    我的python代码如下:

    self.df_census1901['LOC'] = self.df_census1901['LOC'].str.replace(r'/.*?\,', ',')
    self.df_census1901['LOC'] = self.df_census1901['LOC'].str.replace(r'/.*?\)', ')')
    

    1 回复  |  直到 6 年前
        1
  •  1
  •   Sweeper    6 年前

    你可以试试这个正则表达式:

    /.*?(\)|(?: \d+)?,)
    

    r"\1"

    import re
    result = re.sub(r"/.*?(\)|(?: \d+)?,)", r"\1", your_string)
    

    正则表达式的开头与您的相同。把这三种情况结合起来的诀窍是 | (...)? .

    剖析这一部分: (\)|(?: \d+)?,)

    这是一个包含模式的组 \)|(?: \d+)?, ) (?: \d+)?,) . 匹配逗号,可选地在空格后的一组数字后面。

    替换为第1组基本上会用 \)|(?:\d+?, 1, 是匹配的 用于替换。

    Demo