Python 匹配 space 但不匹配换行符的正则表达式

Python Regular Expression to match space but not newline

我有这样一个字符串:

'\n479 Appendix I\n1114\nAppendix I 481\n'

并且想使用正则表达式查找 return

['479 Appendix I', 'Appendix I 481']

我第一次尝试这个表达式:

pattern = r'''
(?: \d+ \s)? Appendix \s+ \w+ (?: \s \d+)?
'''

regex = re.compile(pattern, re.VERBOSE)

regex.findall(s)

但是这个returns

['479 Appendix I\n1114', 'Appendix I 481']

因为 \s 也匹配 \n。 按照此 post 中的其中一个答案, 我尝试了以下方法:

pattern = r'''
(?: \d+ [^ \S\t\n])? Appendix \s+ \w+ (?: [^ \S\t\n] \d+)?
'''

regex = re.compile(pattern, re.VERBOSE)

regex.findall(s)

但是没有 return 想要的结果,给出:

['Appendix I', 'Appendix I']

在这种情况下,什么表达式会起作用?

import re

s = '\n479 Appendix I\n1114\nAppendix I 481\n'

for g in re.findall(r'^.*[^\d\n].*$', s, flags=re.M):
    print(g)

打印:

479 Appendix I
Appendix I 481

此正则表达式将匹配包含至少一个不同于数字或换行符的字符的所有行。 this regex here.

的解释

这个正则表达式比另一个答案中的正则表达式更健壮一些,因为它明确锚定在 "Appendix":

pattern = '(?:\d*[\t ]+)?Appendix\s+\w+(?:[\t ]+\d*)?'
re.findall(pattern, s)
#['479 Appendix I', 'Appendix I 481']