仅当字符不在括号中时才替换字符

时间:2019-01-28 12:03:05

标签: python regex

我有一个如下字符串:

test_string = "test:(apple:orange,(orange:apple)):test2"

仅当括号中不包含“:”时,我才想将其替换为“:”。

所需的输出是“ test /(apple:orange,(orange:apple))/ test2”

这如何在Python中完成?

3 个答案:

答案 0 :(得分:4)

您可以使用下面的代码来达到预期的输出量

def solve(args):
    ans=''
    seen = 0
    for i in args:
        if i == '(':
            seen += 1
        elif i== ')':
            seen -= 1
        if i == ':' and seen <= 0:
            ans += '/'
        else:
            ans += i
    return ans

test_string = "test:(apple:orange,(orange:apple)):test2"
print(solve(test_string))

答案 1 :(得分:2)

带有regex模块:

>>> import regex
>>> test_string = "test:(apple:orange,(orange:apple)):test2"
>>> regex.sub(r'\((?:[^()]++|(?0))++\)(*SKIP)(*F)|:', '/', test_string)
'test/(apple:orange,(orange:apple))/test2'

答案 2 :(得分:0)

  1. 找到第一个开始括号
  2. 找到最后一个右括号
  3. 在第一个左括号之前用“ /”替换每个“:”
  4. 对中间什么都不做
  5. 在最后一个右括号后用“ /”替换每个“:”
  6. 将这3个子字符串放在一起

代码:

test_string = "test:(apple:orange,(orange:apple)):test2"
first_opening = test_string.find('(')
last_closing = test_string.rfind(')')
result_string = test_string[:first_opening].replace(':', '/') + test_string[first_opening : last_closing] +  test_string[last_closing:].replace(':', '/')
print(result_string)

输出:

test/(apple:orange,(orange:apple))/test2

警告:正如评论指出的那样,如果有多个不同的括号,这将不起作用:(