连字符在python2.7正则表达式中

时间:2015-11-19 06:49:52

标签: regex python-2.7 hyphen

pattern = u'''[%-<]'''

txt = '12 of 15 people run into the room'

result = re.sub(pattern, ' ', txt)

>> '   of    people run into the room'

正则表达式如何匹配数字?

编辑:

创建的范围是

enter image description here

1 个答案:

答案 0 :(得分:0)

由于未转义的连字符位于作为范围的字符类中间而发生。

如果你将连字符放在最后或第一个位置,那么它的表现很好:

>>> pattern = ur'[%<-]'
>>> print re.sub(pattern, ' ', txt)
12 of 15 people run into the room

或使用转义连字符:

>>> pattern = ur'[%\-<]'
>>> print re.sub(pattern, ' ', txt)
12 of 15 people run into the room