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

正则匹配<pre>标签内换行并替换的问题:匹配范围异常

解决方法

方案1:代码层面实现(以Python为例)

通过正则捕获整个<pre>块,拆分内部行、去除每行前后空格后,重新为每行包裹<pre>标签:

import re

input_text = "<pre> one\n two\n three\n four\n five\n six </pre>"
# 捕获<pre>标签内的所有内容(支持跨行匹配)
match = re.search(r'<pre>\s*(.*?)\s*</pre>', input_text, re.DOTALL)
if match:
    lines = match.group(1).split('\n')
    # 过滤空行,为有效行添加<pre>标签
    result = ''.join(f'<pre>{line.strip()}</pre>' for line in lines if line.strip())
print(result)

执行后输出:

<pre>one</pre><pre>two</pre><pre>three</pre><pre>four</pre><pre>five</pre><pre>six</pre>

方案2:纯正则替换(适用于VSCode/Sublime等编辑器)

分两步完成替换,需开启编辑器的「正则表达式」模式:

  1. 拆分<pre>内的行并包裹标签

    • 查找正则:
      (?<=<pre>|\G)\s*(.*?)\s*(?=\n|</pre>)
      
    • 替换为:
      <pre>$1</pre>
      

    替换后会得到嵌套的<pre>结构:<pre><pre>one</pre><pre>two</pre>...</pre>

  2. 移除外层嵌套的<pre>标签

    • 查找正则:
      <pre><pre>(.*?)</pre></pre>
      
    • 替换为:
      $1
      

    最终得到目标格式。

原正则的问题

你使用的(?<=<pre>)?(.*)+存在两个核心缺陷:

  • (?<=<pre>)?是可选预查,意味着即使没有<pre>标签也会匹配内容,移除开头<pre>后仍会无差别匹配其他行。
  • 未限制匹配范围在<pre>和</pre>之间,导致匹配逻辑失控。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:55:25