Escape Quotes - 如何转义加号

Escape Quotes -How to escape the plus sign

import re

这是我的尝试

note = r"Call \+201099973073\.Midnight"

note = "Call +201099973073.Midnight"

然后

print(re.search("+201099973073",note))

错误

---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
~/Desktop/modules/regular_exp.py in 
     12 note = "Call +201099973073.Midnight"
     13 
---> 14 print(re.search("+201099973073",note))

/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/re.py in search(pattern, string, flags)
    199     """Scan through string looking for a match to the pattern, returning
    200     a Match object, or None if no match was found."""
--> 201     return _compile(pattern, flags).search(string)
    202 
    203 def sub(pattern, repl, string, count=0, flags=0):

/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/re.py in _compile(pattern, flags)
    302     if not sre_compile.isstring(pattern):
    303         raise TypeError("first argument must be string or compiled pattern")
--> 304     p = sre_compile.compile(pattern, flags)
    305     if not (flags & DEBUG):
    306         if len(_cache) >= _MAXCACHE:

/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/sre_compile.py in compile(p, flags)
    762     if isstring(p):
    763         pattern = p
--> 764         p = sre_parse.parse(p, flags)
    765     else:
    766         pattern = None

/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/sre_parse.py in parse(str, flags, state)
    946 
    947     try:
--> 948         p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)
    949     except Verbose:
    950         # the VERBOSE flag was switched on inside the pattern.  to be

/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/sre_parse.py in _parse_sub(source, state, verbose, nested)
    441     start = source.tell()
    442     while True:
--> 443         itemsappend(_parse(source, state, verbose, nested + 1,
    444                            not nested and not items))
    445         if not sourcematch("|"):

/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/sre_parse.py in _parse(source, state, verbose, nested, first)
    666                 item = None
    667             if not item or item[0][0] is AT:
--> 668                 raise source.error("nothing to repeat",
    669                                    source.tell() - here + len(this))
    670             if item[0][0] in _REPEATCODES:

error: nothing to repeat at position 0
note = r"Call \+201099973073\.Midnight"
print(re.search("+201099973073",note))

需要转义的不是搜索字符串,而是正则表达式。如果您将尝试的转义应用于 search 的第一个参数而不是 note:

,它将起作用
note = "Call +201099973073.Midnight"
print(re.search(r"\+201099973073", note))

输出:

<re.Match object; span=(5, 18), match='+201099973073'>