You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用正则表达式移除文本中指定格式的Page类页码内容

现有代码的核心问题

  • 正则表达式语法错误:字符串拼接逻辑错误、未匹配多位数字、未处理页码前后的可变空格
  • re.sub 参数顺序错误,正确顺序为正则模式, 替换内容, 原文本, 标志位,你的代码把原文本和替换内容位置写反了
  • 未处理页码前后的多余空格,直接替换会留下无意义空白字符

正确实现代码

import re

text = "Page 1 of 28 Medical Policies Archived Policies - Radiology Print Percutaneous Balloon Kyphoplasty, Radiofrequency Kyphoplasty, and Mechanical  Page 2/3 Percutaneous radiofrequency kyphoplasty or percutaneous mechanical vertebral augmentation using any other device, including but not limited. Page 38 Percutaneous Balloon Kyphoplasty, Radiofrequency Kyphoplasty, and Me... While radiotherapy and chemotherapy are frequently "

# 正则同时适配三种页码格式,同步处理前后空格避免残留空白
pattern = r'\bPage\s+\d+(?:\s+of\s+\d+|/\d+)?\b\s*'
adm = re.sub(pattern, '', text, flags=re.IGNORECASE)

print(adm)

正则规则说明

  • \b 匹配单词边界,避免误删包含Page的普通英文单词
  • Page\s+ 匹配Page+1个或多个空格,适配Page和数字之间空格数量不固定的情况
  • \d+ 匹配1位及以上数字,适配个位数、多位数页码
  • (?:\s+of\s+\d+|/\d+)? 非捕获组,匹配两种可选后缀:
    • \s+of\s+\d+ 对应「Page X of Y」格式
    • /\d+ 对应「Page X/Y」格式
    • 末尾?表示后缀可选,适配只有「Page X」的格式
  • \s* 匹配页码后0个或多个空格,替换后不会留下多余空白

运行后输出结果:

Medical Policies Archived Policies - Radiology Print Percutaneous Balloon Kyphoplasty, Radiofrequency Kyphoplasty, and Mechanical  Percutaneous radiofrequency kyphoplasty or percutaneous mechanical vertebral augmentation using any other device, including but not limited. Percutaneous Balloon Kyphoplasty, Radiofrequency Kyphoplasty, and Me... While radiotherapy and chemotherapy are frequently 

内容的提问来源于stack exchange,提问作者user17142920

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 09:57:06