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

如何仅移除字符串中单词内部的标点符号?

移除单词内部标点,保留首尾标点

需求说明

移除字符串中单词内部的所有标点符号,保留单词开头或结尾的标点。示例:we'll 转为 well,We're 转为 Were;而 build,、crazy! 这类首尾的标点需保留。

测试输入示例:

let testString = "What's with this project I'm trying to build, it's cra!zy!"

已尝试的缺陷方案

1. 逐个指定标点移除

if let resultRange = myString.range(of: "'") {
    let startIndex = resultRange.lowerBound
    let endIndex = resultRange.upperBound
    let range = startIndex..<endIndex
    let result = myString.replacingCharacters(in: range, with: "")
    print(result) // 输出:"Whats with this project Im trying to build, its cra!zy"

问题:只能手动指定要移除的标点,遇到新标点需新增判断,扩展性极差,无法覆盖全量标点类型。

2. 移除所有标点

extension String {
  func removingCharacters(inCharacterSet forbiddenCharacters:CharacterSet) -> String
{
    var filteredString = self
    while true {
      if var forbiddenCharRange = filteredString.rangeOfCharacter(from: forbiddenCharacters)  {
        filteredString.removeSubrange(forbiddenCharRange)
      }
      else {
        break
      }
    }

    return filteredString
  }
}

var resultMyString = myString.removingCharacters(inCharacterSet: .punctuationCharacters)
print(resultMyString) // 输出:"Whats with this project Im trying to build its crazy"

问题:会一并移除单词首尾的标点,比如build,变成build、crazy!变成crazy,不符合需求。

期望输出

"Whats with this project Im trying to build, its crazy!"

解决方案

使用正则表达式精准匹配「前后都被字母包围的标点」(即单词内部标点),再将其替换为空字符串。Swift实现如下:

extension String {
    func removeInnerPunctuation() -> String {
        // 正则规则:匹配前后均为字母的标点符号
        let pattern = "(?<=\\p{L})\\p{P}(?=\\p{L})"
        return self.replacingOccurrences(of: pattern, with: "", options: .regularExpression)
    }
}

// 测试验证
let testString = "What's with this project I'm trying to build, it's cra!zy!"
let result = testString.removeInnerPunctuation()
print(result) // 输出:"Whats with this project Im trying to build, its crazy!"

正则规则说明

  • (?<=\\p{L}):正向预查,确保标点前是任意Unicode字母
  • \\p{P}:匹配任意Unicode标点符号,覆盖所有标点类型
  • (?=\\p{L}):正向预查,确保标点后是任意Unicode字母

该方案可精准移除单词内部标点,同时完整保留首尾标点。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 17:55:26