您可以使用
(?<!\w)(your|escaped|keywords|here)\W*([A-Z]*\d+(?:-+[A-Z]*\d+)*)
See the 正则表达式演示 https://regex101.com/r/zsB5xC/1.
图案细节
-
(?<!\w)
- 左词边界(明确,\b
含义取决于上下文,如果下一个字符是非单词字符,则它将需要左侧有一个单词字符,而这不是用户通常期望的)
-
(your|escaped|keywords|here)
- 捕获组 1:您的关键字列表,可以使用轻松构建'|'.join(map(re.escape,my_list))
(note re.escape
有必要转义特殊的正则表达式元字符,例如.
, +
, (
, [
, etc.)
-
\W*
- 0+ 个非单词字符(字母、数字或字符以外的字符)_
)
-
([A-Z]*\d+(?:-+[A-Z]*\d+)*)
- Capturing group 2:
-
[A-Z]*
- 零个或多个大写 ASCII 字母
-
\d+
- 1 位或多位数字
-
(?:-+[A-Z]*\d+)*
- 0 or more repetitions of
-
-+
- 一个或多个连字符
-
[A-Z]*\d+
- 零个或多个大写 ASCII 字母、1 个或多个数字
See the Python演示 https://ideone.com/tAVzIi:
import re
s="""your_text_here"""
my_list = ['Ref.:', 'Reference', 'tramite', 'Expediente', 'Expediente No', 'Expedien N°', 'Exp.No', 'Expedien']
rx = r'(?<!\w)({})\W*([A-Z]*\d+(?:-+[A-Z]*\d+)*)'.format('|'.join(map(re.escape,my_list)))
print(re.findall(rx, s))
Output:
[('Expedien', '1-21-212-16-26'), ('Reference', 'RE9833'), ('tramite', '1234567'), ('Expedien N°', '18-00777'), ('Expedien N°', '18-0022995')]