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

Swift 5如何使用正则表达式移除字符串中的LaTex \text{...}片段?

Swift 5 移除LaTeX中\text{...}片段的实现方案

核心正则逻辑

要完全匹配所有\text{...}片段(包括内部存在嵌套大括号的复杂场景),需要使用支持平衡括号匹配的递归正则模式:
\\text\s*(\{(?:[^{}]|(?1))*\})
各部分含义:

  • \\text 匹配字面量\text字符串
  • \s* 兼容\text与左大括号之间的任意空白字符(空格、换行、制表符等)
  • 括号内的递归逻辑自动匹配成对的大括号,处理多层嵌套场景,避免普通非贪婪匹配提前截断的问题

代码实现

Swift 5.7+ 原生Regex实现(推荐)

import Foundation

func removeTextCommands(from latexString: String) -> String {
    let textRegex = /\\text\s*(\{(?:[^{}]|(?1))*\})/
    return latexString.replacing(textRegex, with: "")
        .trimmingCharacters(in: .whitespacesAndNewlines)
}

低版本Swift兼容实现(基于NSRegularExpression)

import Foundation

func removeTextCommandsLegacy(from latexString: String) throws -> String {
    let pattern = "\\\\text\\s*(\\{(?:[^{}]|(?1))*\\})"
    let regex = try NSRegularExpression(pattern: pattern, options: [])
    let fullRange = NSRange(latexString.startIndex..., in: latexString)
    return regex.stringByReplacingMatches(in: latexString, range: fullRange, withTemplate: "")
        .trimmingCharacters(in: .whitespacesAndNewlines)
}

测试效果

  • 输入\text { c. } 50 \times 14 → 输出50 \times 14
  • 输入\text { d. } 180 \div 5 → 输出180 \div 5
  • 输入\text{外层 \text{嵌套内容} 收尾} \sqrt{2} + 1 → 输出\sqrt{2} + 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:45:04