sre_constants.error:正则表达式意外结束 - 应该可以正常工作 [英] sre_constants.error: unexpected end of regular expression - Should Work Fine

查看:136
本文介绍了sre_constants.error:正则表达式意外结束 - 应该可以正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在做一些测试,我需要一种将字符串分成两组的方法.(例如 'abcdef' => ['ab','cd','ef'])

So I'm doing a little bit of testing for something and I require a method of splitting a string into groups of two. (e.g. 'abcdef' => ['ab','cd','ef'])

我正在尝试使用正则表达式模式来执行此操作 ([^]{2}).每当我尝试编译此模式时,都会收到错误消息:

I'm trying to use a regex pattern to do this ([^]{2}). Whenever I try to compile this pattern, I get the error message:

sre_constants.error: 正则表达式意外结束

sre_constants.error: unexpected end of regular expression

确切的代码行是:
pat = re.compile(r'[^]{2}')

有人可以告诉我我在这里做错了什么吗?我进行了大量搜索,但很多问题都与使用不当和/或反斜杠有关.

Could someone please tell me what I'm doing wrong here? I've done a lot of searching but a lot of the problems were related to incorrect usage and/or backslashes.

我认为这可能是因为字符串格式,尽管 Python 文档没有提到任何问题.

I thought about it possibly being because of string formatting, though the Python docs didn't mention anything about any issues.

推荐答案

使用

(.{2})

点将匹配任何字符.如果你想用点匹配换行符,不要忘记添加 s 修饰符.所以你的代码看起来像这样

Dot will match any character. If you want to match newline characters with dot do not forget to add s modifier. So your code will look like this

p = re.compile('(?s)(.{2})')

此外,我不确定您为什么要在任务中使用正则表达式.您可以使用以下代码段来完成

Also I am not sure why you want to use regular expressions for the task. You can do it with following snippet

In [5]: line = 'abcdef'

In [6]: n = 2

In [7]: [line[i:i+n] for i in xrange(0, len(line), n)]
Out[7]: ['ab', 'cd', 'ef']

这篇关于sre_constants.error:正则表达式意外结束 - 应该可以正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆