python - 正则表达式意外结束

标签 python regex python-3.3

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

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'

关于python - 正则表达式意外结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26403986/

相关文章:

javascript - 舍入 javascript 字符串并显示不带小数的美元格式

regex - 如何仅匹配一个字母词

python - 基于从 Pandas DataFrame 中其他 2 列的值进行条件选择的新列

python - 使用 psycopg2 与 postgresql 的连接被拒绝

python - 适用于 Windows 的 Mongodb 电机驱动程序

Javascript - 匹配一个长 5 位数字的正则表达式

在 virtualenv 中全局安装 Python3 pip

python - 在不破坏现有回调的情况下将额外的可选参数传递给回调

python - 如何设置whisper.DecodingOptions语言?

python - 如何检查列表的元素是否连续