Python 更改模式顺序时,正则表达式搜索不起作用
我正在写一个小正则表达式来过滤字符串中的电子邮件。当我将模式用作Python 更改模式顺序时,正则表达式搜索不起作用,python,regex,Python,Regex,我正在写一个小正则表达式来过滤字符串中的电子邮件。当我将模式用作patt=r'[\w.-]+@[\w.-]+'时,它工作正常。但是当我使用模式作为patt1=r'[\w-.]+@[\w-.]+'时,它会给我错误: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.f
patt=r'[\w.-]+@[\w.-]+'
时,它工作正常。但是当我使用模式作为patt1=r'[\w-.]+@[\w-.]+'
时,它会给我错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 146, in search
return _compile(pattern, flags).search(string)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 251, in _compile
raise error, v # invalid expression
sre_constants.error: bad character range
第2例:
>>> str = "hello@abc.com"
>>> patt = r'[\w-.]+@[\w-.]+'
>>> match = re.search(patt, str)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 146, in search
return _compile(pattern, flags).search(string)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 251, in _compile
raise error, v # invalid expression
sre_constants.error: bad character range
>>str=”hello@abc.com"
>>>patt=r'[\w-.]+@[\w-.]+'
>>>匹配=重新搜索(patt,str)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py”,搜索中的第146行
返回编译(模式、标志)。搜索(字符串)
文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py”,第251行,在编译中
raise错误,v#表达式无效
sre_常量。错误:错误的字符范围
知道我在第二个正则表达式中做错了什么吗?连字符
-
必须是列表中的第一个或最后一个。当在两个字符之间使用它们来表示一个范围时,它们具有特殊的含义,如[a-Z]
(所有大写字母)。当连字符位于结尾或开头时,它没有特殊意义
此外,转义它\-
在Python中也可以工作,但要注意,它在其他实现/语言中可能不起作用
请在此处查看已接受的答案:
与您的问题不完全相同,但涉及到类似的信息。字符类([]
)内的破折号(-
)表示字符范围,即从到。因此,如果您想使用literal-
,您有3个选项:
- 将
放在开头:-
[-foo]
- 将
放在末尾:-
[foo-]
- 用
转义\
:-
[foo \-bar]
\w-
字符类中存在连字符,所以python将其解释为字符间隔。
>>> str = "hello@abc.com"
>>> patt = r'[\w-.]+@[\w-.]+'
>>> match = re.search(patt, str)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 146, in search
return _compile(pattern, flags).search(string)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 251, in _compile
raise error, v # invalid expression
sre_constants.error: bad character range