![](/img/trans.png)
[英]how write python re.sub pattern Ignore single or double quotes?
[英]Python re.sub to remove single quotes AND double quotes from string
這是一個很快讓我發瘋的問題。 我想從字符串中刪除 ' 和 " 字符。我想用 re.sub 來做(因為我想比較 re.sub 和 str.replace 所以我想兩種方式都做)。現在我的理解原始字符串的優點是轉義字符被視為文字,除非它們是 escaping 打開字符串的字符。所以我有兩個想法如何做到這一點:
# 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)是正確的說法嗎? 你能幫我理解這是怎么回事嗎?
當您顯示它們的值時,它們看起來不同,但就被解釋為正則表達式而言,它們是等價的:
import re
REGEX1 = re.compile(r"[" + r'"' + r"'" + r"]")
print(REGEX1.pattern)
print(REGEX1.sub('', """abc"'def"""))
REGEX2= re.compile(r"[\"']")
print(REGEX2.pattern)
print(REGEX2.sub('', """abc"'def"""))
印刷:
["']
abcdef
[\"']
abcdef
解釋
原始字符串r'\n'
和非原始字符串'\n'
之間的區別是巨大的,因為后者是一個特殊的轉義序列,相當於換行符,而前者相當於'\\n'
,即反斜杠后跟字母 n 的兩個字符序列。 但對於其他情況,例如'\"
,其中后跟雙引號的反斜杠不是特殊的轉義序列,那么反斜杠是多余的並且可以忽略,因此["']
和[\"']
是等價的。
更新
由於我指出當反斜杠后面的內容在反斜杠后面具有特殊含義時(例如r'\n'
與'\n'
),原始字符串與非原始字符串中的轉義序列通常存在很大差異,對於正則表達式的所有意圖和目的而言,情況並非總是如此。 例如,在正則表達式中使用時,Python 正則表達式引擎會將換行符與從雙字符序列r'\n'
(即'\\n'
)編譯的正則表達式或換行符匹配'\n'
:
import re
REGEX1 = re.compile('a\nb') # use actual newline
print('pattern1 = ', REGEX1.pattern)
print(REGEX1.search('a\nb'))
REGEX2 = re.compile(r'a\nb') # use '\\n'
print('pattern 2 =', REGEX2.pattern)
print(REGEX2.search('a\nb'))
印刷:
pattern1 = a
b
<re.Match object; span=(0, 3), match='a\nb'>
pattern 2 = a\nb
<re.Match object; span=(0, 3), match='a\nb'>
但是,由於您可能需要的情況,通常使用原始字符串,例如, r'\1'
返回捕獲組 1 並且'\1'
會匹配'\x01'
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.