删除引号之间的所有逗号

时间:2016-07-12 18:36:07

标签: python regex

我试图用python删除引号内的所有逗号("):

'please,remove all the commas between quotes,"like in here, here, here!"'
                                                          ^     ^

我尝试了这个,但它只删除了引号中的第一个逗号:

re.sub(r'(".*?),(.*?")',r'\1\2','please,remove all the commas between quotes,"like in here, here, here!"')

输出:

'please,remove all the commas between quotes,"like in here here, here!"'

如何删除引号内的所有逗号?

4 个答案:

答案 0 :(得分:13)

假设您没有不平衡或转义的报价,您可以根据负前瞻使用此正则表达式:

>>> str = r'foo,bar,"foobar, barfoo, foobarfoobar"'
>>> re.sub(r'(?!(([^"]*"){2})*[^"]*$),', '', str)
'foo,bar,"foobar barfoo foobarfoobar"'

这个正则表达式会找到逗号,如果它们在双引号内,则使用否定前瞻来断言逗号后面甚至没有引号数。

关于lookaead (?!...)的注意事项:

  • ([^"]*"){2}找到一对引号
  • (([^"]*"){2})*找到0对或更多引号
  • [^"]*$确保在最后一次匹配的报价后我们没有其他报价
  • 所以(?!...)断言我们前面没有引号,因此仅匹配引号字符串中的逗号。

答案 1 :(得分:3)

您可以将函数作为repl参数传递,而不是替换字符串。只需获取整个带引号的字符串,并在逗号上执行简单的字符串替换。

>>> s = 'foo,bar,"foobar, barfoo, foobarfoobar"'
>>> re.sub(r'"[^"]*"', lambda m: m.group(0).replace(',', ''), s)
'foo,bar,"foobar barfoo foobarfoobar"'

答案 2 :(得分:1)

如果您不想使用正则表达式,我会提出另一个选项。

input_str = 'please,remove all the commas between quotes,"like in here, here, here!"'

quotes = False

def noCommas(string):
    quotes = False
    output = ''
    for char in string:
        if char == '"':
            quotes = True
        if quotes == False:
            output += char
        if char != ',' and quotes == True:
            output += char
    return output

print noCommas(input_str)

答案 3 :(得分:0)

用正则表达式做什么呢?

input_str = '...'

first_slice = input_str.split('"')

second_slice = [first_slice[0]]
for slc in first_slice[1:]:
    second_slice.extend(slc.split(','))

result = ''.join(second_slice)