【发布时间】:2021-02-26 22:14:11
【问题描述】:
这是一个很快让我发疯的问题。我想从字符串中同时删除 ' 和 " 字符。我想使用 re.sub 来做到这一点(因为我正在尝试比较 re.sub 与 str.replace 所以我想同时做到这一点)。现在我的理解原始字符串的最大特点是转义字符被视为文字,除非它们正在转义打开字符串的字符。所以我有两个想法如何做到这一点:
# Method 1: concatenate strings that have different enclosing characters
>>> REGEX1 = re.compile(r"[" + r'"' + r"'" + r"]")
>>> REGEX1.pattern
'["\']'
# Method 2: Try to escape one of the quotation characters
>>> REGEX2= re.compile(r"[\"']")
>>> REGEX2.pattern
'[\\"\']'
给出的模式看起来不同。他们是吗?我测试它们在正则表达式中的行为是否相同:
>>> test_string = "hello ' world \" "
>>> test_string
'hello \' world " '
>>> result_1 = REGEX1.sub(r'', test_string)
>>> result_2 = REGEX2.sub(r'', test_string)
>>> result_1
'hello world '
>>> result_2
'hello world '
>>>
我的直觉告诉我有两种可能:
- '["']' == '[\"']'
- '["']' != '[\"']',但在作为正则表达式处理时表现相同。
那么最后一个测试:
>>> '["\']' == '[\\"\']'
False
那么上面的 2) 是正确的说法吗?你能帮我理解发生了什么吗?
【问题讨论】:
标签: python regex string re rawstring