查找字符串中引号内的字符

Gar*_*abo 3 string swift swift3

我正在尝试提取字符串中引号中的部分,即“"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))
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 5

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

  • 用于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"
}
Run Code Online (Sandbox Code Playgroud)

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

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