【问题标题】:Regex pattern match and replace in SwiftSwift 中的正则表达式模式匹配和替换
【发布时间】:2023-03-26 06:15:01
【问题描述】:

我有如下字符串:

Hi this is %1$s, product %2$s Hi this is %2$s, product %2$s

我想用 {0} 替换 %1$s,用 {1} 替换 %2$s 等等。

我已经尝试过:

let range = NSRange(location: 0, length: myString.count)
var regex = try! NSRegularExpression(pattern: "%[1-9]\\$s", options: [])
var newStr = regex.stringByReplacingMatches(in: myString, options: [], range: range, withTemplate: "XXXX")

任何人都可以帮助我,拜托!

【问题讨论】:

  • 你可以试试这个。 let newString = aString.replacingOccurrences(of: "%2$s ", with: "1")
  • 它不起作用
  • 快速提问:[a-z] 在你的模式开头是什么意思?您是否使用在线正则表达式工具尝试了您的正则表达式?
  • 对不起,我后来删除了,但忘记在这里更新了
  • 现在的问题是它用相同的数字替换所有出现让我们说 {1} 预期的行为是 {1},然后是 {2}

标签: ios swift regex string


【解决方案1】:

你的模式是错误的,你一开始就有[a-z],所以你没有检测到任何东西。

另外,NSStuff 更喜欢 utf16 计数(因为使用 NSString,它是 UTF16)

let myString = "Hi this is %1$s, product %2$s Hi this is %2$s, product %2$s"

let range = NSRange(location: 0, length: myString.utf16.count)
var regex = try! NSRegularExpression(pattern: "%(\\d+)\\$s", options: [])
var newStr = regex.stringByReplacingMatches(in: myString, options: [], range: range, withTemplate: "{$1}")
print(newStr)

输出:

$>Hi this is {1}, product {2} Hi this is {2}, product {2}

%(\d+)\$s 的一些解释(然后为 Swift 字符串重做 \)。
%:检测“%”
\d+:检测数字(包括 12 个不是你的之前的情况)
(\d+):检测号码,但在捕获组中
\$:检测“$”(需要转义,因为它是正则表达式中的特殊字符)
s:检测“ s"

所以有两组:整体(对应于整个正则表达式匹配)和数字。第一个是 0 美元,第二个是 1 美元,这就是我在模板中使用 {$1} 的原因。

注意:我使用https://regex101.com 来检查模式。

有了增量,你不能用模板来做。您必须枚举所有匹配项,进行操作并替换。

var myString = "Hi this is %1$s, product %2$s Hi this is %2$s, product %2$s"
let range = NSRange(location: 0, length: myString.utf16.count)
var regex = try! NSRegularExpression(pattern: "%(\\d+)\\$s", options: [])
let matches = regex.matches(in: myString, options: [] , range: range)
matches.reversed().forEach({ aMatch in
    let fullNSRange = aMatch.range
    guard let fullRange = Range(fullNSRange, in: myString) else { return }
    let subNSRange = aMatch.range(at: 1)
    guard let subRange = Range(subNSRange, in: myString) else { return }
    let subString = myString[subRange]
    guard let subInt = Int(subString) else { return }
    let replacement = "{" + String(subInt + 1) + "}"
    myString.replaceSubrange(fullRange, with: replacement)
})

【讨论】:

  • 你刚刚拯救了我的一天!非常感谢
  • 嗨@Larme 我可以问你一个问题,如果我想将每个 no 减去 1 会怎样:myString = "嗨,这是 {0},产品 {1},..."
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多