gpt4 book ai didi

swift - 在字符串中查找引号内的字符

转载 作者:搜寻专家 更新时间:2023-11-01 05:52:45 24 4
gpt4 key购买 nike

我正在尝试提取引号中的字符串部分,即在 "Rouge One"is an awesome movie 中,我想提取 Rouge One。

这是我目前所拥有的,但无法弄清楚从这里去哪里:我创建了文本的副本,这样我就可以删除第一个引号,这样我就可以获得第二个引号的索引。

if text.contains("\"") {
guard let firstQuoteMarkIndex = text.range(of: "\"") else {return}
var textCopy = text
let textWithoutFirstQuoteMark = textCopy.replacingCharacters(in: firstQuoteMarkIndex, with: "")
let secondQuoteMarkIndex = textCopy.range(of: "\"")
let stringBetweenQuotes = text.substring(with: Range(start: firstQuoteMarkIndex, end: secondQuoteMarkIndex))
}

最佳答案

无需为此任务创建副本或替换子字符串。这是一种可能的方法:

  • 使用 text.range(of: "\"") 找到第一个引号。
  • 使用 text.range(of: "\"", range:...) 找到第二个引号,即找到的范围之后的第一个引号在第 1 步中。
  • 提取两个范围之间的子字符串。

例子:

let text = "  \"Rouge One\" is an awesome movie"

if let r1 = text.range(of: "\""),
let r2 = text.range(of: "\"", range: r1.upperBound..<text.endIndex) {

let stringBetweenQuotes = text.substring(with: r1.upperBound..<r2.lowerBound)
print(stringBetweenQuotes) // "Rouge One"
}

另一种选择是使用“正向后视”和“正向前视”模式的正则表达式搜索:

if let range = text.range(of: "(?<=\\\").*?(?=\\\")", options: .regularExpression) {
let stringBetweenQuotes = text.substring(with: range)
print(stringBetweenQuotes)
}

关于swift - 在字符串中查找引号内的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41351393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com