[英]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
匹配一個空格和1
[^\S\r\n]*
匹配 0+ 次出現的空白字符,換行符除外[:.;–-]?
可選匹配字符 class 中列出的任何一個示例代碼也匹配字符 class 之后的空格:
caption = re.sub(r'\bfig\.?(?:ure)? 1[^\S\r\n]*[:.;–-]?[^\S\r\n]', '', caption, flags=re.IGNORECASE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.