sre_constants.error: unexpected end of regular expression - Should Work Fine

情到浓时终转凉″ 提交于 2021-02-08 07:29:56

问题


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'])

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: unexpected end of regular expression

The exact line of code is:
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.

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


回答1:


Use

(.{2})

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']



回答2:


It is true that in JavaScript [^] means "match any character" (though even regex101 says: "Note: Avoid this construct, use . or [\s\S] instead."). However, in Python, [^] is an invalid character class (see this example on regex101).

Use (?s)(.{2}).

See demo.

(?s) inline option will make sure you also match the newline characters.



来源:https://stackoverflow.com/questions/29917384/sre-constants-error-unexpected-end-of-regular-expression-should-work-fine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!