【问题标题】:Replace character in parentheses with another用另一个替换括号中的字符
【发布时间】:2018-12-03 14:12:20
【问题描述】:

我需要用其他东西(例如分号)替换所有出现的点,但前提是点是双亲,像这样使用python:

输入:"Hello (This . will be replaced, this one. too)."
输出:"Hello (This ; will be replaced, this one; too)."

【问题讨论】:

  • 括号可以嵌套吗?你尝试了什么?
  • 你可以做一些关于使用正则表达式的研究吗?
  • 只提出问题而不尝试解决它通常会吸引反对票或关闭请求。
  • 你试过什么没用?
  • 对不起,我的第一篇文章,不是一个好的 ig,我可以在括号外替换它并在括号内替换整个字符串,但我无法将两者结合在一起。下次会尝试更好的,还有,父母不会嵌套。

标签: python regex string python-3.x


【解决方案1】:

假设括号是平衡的而不是嵌套的,这是re.split的一个想法。

>>> import re
>>> 
>>> s = 'Hello (This . will be replaced, this one. too). This ... not but this (.).'
>>> ''.join(m.replace('.', ';') if m.startswith('(') else m
...:        for m in re.split('(\([^)]+\))', s))
...:        
'Hello (This ; will be replaced, this one; too). This ... not but this (;).'

这里的主要技巧是将正则表达式 \([^)]+\) 与另一对 () 包装起来,以便保留拆分匹配。

【讨论】:

    【解决方案2】:

    循环遍历字符串中的字符,跟踪左括号和右括号的数量,仅当遇到的左括号多于右括号时才替换。

    def replace_inside_parentheses(string, find_string, replace_string):
        bracket_count = 0
        return_string = ""
        for a in string:
            if a == "(":
                bracket_count += 1
            elif a == ")":
                bracket_count -= 1
            if bracket_count > 0:
                return_string += a.replace(find_string, replace_string)
            else:
                return_string += a
        return return_string
    
    
    my_str = "Hello (This . will be replaced, this one. too, (even this one . inside nested parentheses!))."
    print(my_str)
    print(replace_inside_parentheses(my_str, ".", ";"))
    

    【讨论】:

      【解决方案3】:

      不是最优雅的方式,但这应该可行。

      def sanitize(string):
          string = string.split("(",1)
          string0 = str(string[0])+"("
          string1 = str(string[1]).split(")",1)
          ending  = str(")"+string1[1])
          middle  = str(string1[0])
      
          # replace second "" with character you'd like to replace with
          # I.E. middle.replace(".","!")
          middle  = middle.replace(".","").replace(";","")
      
          stringBackTogether = string0+middle+ending
          return stringBackTogether
      
      a = sanitize("Hello (This . will be replaced, this one. too).")
      print(a)
      

      【讨论】:

        猜你喜欢
        • 2021-08-20
        • 1970-01-01
        • 1970-01-01
        • 2015-04-16
        • 1970-01-01
        • 2014-08-14
        • 1970-01-01
        • 1970-01-01
        • 2020-02-08
        相关资源
        最近更新 更多