如何解决转义行情 - 如何转义加号
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,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,verbose,nested)
441 start = source.tell()
442 while True:
--> 443 itemsappend(_parse(source,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,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'>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。