Python 变量宽度的正向查看分割

1 投票
3 回答
748 浏览
提问于 2025-04-18 00:34

我以为我设置的表达式是正确的,但分割功能没有按预期工作。

c = re.compile(r'(?<=^\d\.\d{1,2})\s+');
for header in ['1.1 Introduction', '1.42 Appendix']:
    print re.split(c, header)

我期望的结果是:

['1.1', 'Introduction']
['1.42',  'Appendix']

但是我得到了以下的错误信息:

追踪记录(最近的调用在最前面):
     文件 "foo.py",第 1 行,
          c = re.compile(r'(?<=^\d.\d{1,2})\s+');
     文件 "C:\Python27\lib\re.py",第 190 行,
          返回 _compile(pattern, flags)
     文件 "C:\Python27\lib\re.py",第 242 行,
          引发错误,v # 表达式无效
sre_constants.error: 反向查找需要固定宽度的模式
<<< 进程结束。 (退出代码 1)

3 个回答

0

我的解决方案可能看起来不太高明。不过,你只是在检查小数点后面的两个数字。所以,你可以使用两个向后查找。

c = re.compile(r'(?:(?<=^\d\.\d\d)|(?<=^\d\.\d))\s+');
1

你在正则表达式中的错误在于 {1,2} 这一部分,因为向后查找的长度必须是固定的,所以不允许使用数量词。

你可以试试这个 网站,在把正则表达式放进代码之前先测试一下。

不过在你的情况下,其实根本不需要使用正则表达式:

你可以简单地试试这个:

for header in ['1.1 Introduction', '1.42 Appendix']:
    print header.split(' ')

结果:

['1.1', 'Introduction']
['1.42', 'Appendix']

希望这能帮到你。

4

在Python中,向后查找的长度不能是可变的,所以你的向后查找是不合法的。

你可以使用捕获组作为解决方法:

c = re.compile(r'(^\d\.\d{1,2})\s+');
for header in ['1.1 Introduction', '1.42 Appendix']:
    print re.split(c, header)[1:] # Remove the first element because it's empty

输出结果:

['1.1', 'Introduction']
['1.42', 'Appendix']

撰写回答