Skip to main content
 首页 » 编程设计

python之正则表达式意外结束

2025年05月04日31haluo1

我只想从路径中获取带扩展名的文件名:

C:\\Users\\anandada\\workspace\\MyTestProject\\src\\OpenTest.c 

下面的语句,

fileName = re.match("[^\\]*.c$", fileName) 

给出错误:

unexpected end of regular expression

我正在使用 python 3.3.2

请您参考如下方法:

您需要加倍加倍转义再次,或改用原始字符串:

fileName = re.match("[^\\\\]*.c$",fileName) 

或

fileName = re.match(r"[^\\]*.c$",fileName) 

否则首先是 Python,然后正则表达式编译器将解释这些反斜杠,导致 ] 被转义:

>>> print("[^\\]*.c$") 
'[^\]*.c$' 

另见 Blackslash Plague section Python 正则表达式指南。

接下来,您需要注意 re.match 锚定到字符串的开头。您可能希望在这里使用 re.search()。查看match() vs. search() section :

The match() function only checks if the RE matches at the beginning of the string while search() will scan forward through the string for a match. It’s important to keep this distinction in mind.

您可能还想转义 .c 部分中的 .; . 匹配任何字符,所以 foobaric 也会匹配; i 将满足 . 模式。

re.match() 和 re.search() 函数返回 match object ,而不是字符串的匹配部分。您必须明确提取该部分:

fileName = re.search(r'[^\\]*\.c$', fileName).group() 

演示:

>>> import re 
>>> fileName = 'C:\\Users\\anandada\\workspace\\MyTestProject\\src\\OpenTest.c' 
>>> re.search(r'[^\\]*\.c$', fileName).group() 
'OpenTest.c'