Python正则表达式:替换子字符串的多种可能性
Python Regex: replace multiple possibilities of substring
我想删除字符串 caption
中的指标 Fig 1.
,其中 caption
可能是:
# each line is one instance of caption
"Figure 1: Path of Reading Materials from the Web to a Student."
"FIGURE 1 - Travel CP-net"
"Figure 1 Interpretation as abduction, the big picture."
"Fig. 1. The feature vector components"
"Fig 1: IMAGACT Log-in Page"
"FIG 1 ; The effect of descriptive and interpretive information, and Inclination o f Fit"
...
我试过caption = re.sub(r'figure 1: |fig. 1 |figure 1 -', '', caption, flags=re.IGNORECASE)
,但看起来很乱:我真的需要手动列出所有可能性吗?是否有任何元素重新编码来匹配它们?
非常感谢!
您可以使用可选部分来匹配 ure
,并使用可选字符 class 来匹配 :
、.
、;
或 -
如果要匹配除 1 以外的其他数字,请使用 \d+
\bfig\.?(?:ure)? 1[^\S\r\n]*[:.;–-]?
\bfig
匹配前面有单词边界的 fig
\.?
匹配一个可选的点
(?:ure)?
可选匹配 ure
1
匹配一个space和1
[^\S\r\n]*
匹配出现 0 次以上的白色 space 字符,换行符除外
[:.;–-]?
可选地匹配字符 class 中列出的任何一个
示例代码也匹配字符 class 之后的白色 space:
caption = re.sub(r'\bfig\.?(?:ure)? 1[^\S\r\n]*[:.;–-]?[^\S\r\n]', '', caption, flags=re.IGNORECASE)
我想删除字符串 caption
中的指标 Fig 1.
,其中 caption
可能是:
# each line is one instance of caption
"Figure 1: Path of Reading Materials from the Web to a Student."
"FIGURE 1 - Travel CP-net"
"Figure 1 Interpretation as abduction, the big picture."
"Fig. 1. The feature vector components"
"Fig 1: IMAGACT Log-in Page"
"FIG 1 ; The effect of descriptive and interpretive information, and Inclination o f Fit"
...
我试过caption = re.sub(r'figure 1: |fig. 1 |figure 1 -', '', caption, flags=re.IGNORECASE)
,但看起来很乱:我真的需要手动列出所有可能性吗?是否有任何元素重新编码来匹配它们?
非常感谢!
您可以使用可选部分来匹配 ure
,并使用可选字符 class 来匹配 :
、.
、;
或 -
如果要匹配除 1 以外的其他数字,请使用 \d+
\bfig\.?(?:ure)? 1[^\S\r\n]*[:.;–-]?
\bfig
匹配前面有单词边界的 fig\.?
匹配一个可选的点(?:ure)?
可选匹配ure
1
匹配一个space和1
[^\S\r\n]*
匹配出现 0 次以上的白色 space 字符,换行符除外[:.;–-]?
可选地匹配字符 class 中列出的任何一个
示例代码也匹配字符 class 之后的白色 space:
caption = re.sub(r'\bfig\.?(?:ure)? 1[^\S\r\n]*[:.;–-]?[^\S\r\n]', '', caption, flags=re.IGNORECASE)