在String中查找引号内的字符

时间:2016-12-27 19:55:14

标签: swift string 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))
}

4 个答案:

答案 0 :(得分:3)

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

  • 使用text.range(of: "\"", range:...)查找第一个引号。
  • 使用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" } 查找第二个引号,即在步骤1中找到的范围后的第一个
  • 提取两个范围之间的子字符串。

示例:

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

另一种选择是使用&#34;正面观察&#34;正则表达式搜索并且&#34;积极向前看&#34;图案:

->fetch

答案 1 :(得分:1)

var rouge = "\"Rouge One\" is an awesome movie"

var separated = rouge.components(separatedBy: "\"") // ["", "Rouge One", " is an awesome movie"]

separated.dropFirst().first

答案 2 :(得分:1)

另一个选择是使用regular expressions查找引号对:

let pattern = try! NSRegularExpression(pattern: "\\\"([^\"]+)\\\"")

// Small helper methods making it easier to work with enumerateMatches(in:...)
extension String {
    subscript(utf16Range range: Range<Int>) -> String? {
        get {
            let start = utf16.index(utf16.startIndex, offsetBy: range.lowerBound)
            let end = utf16.index(utf16.startIndex, offsetBy: range.upperBound)
            return String(utf16[start..<end])
        }
    }

    var fullUTF16Range: NSRange {
        return NSRange(location: 0, length: utf16.count)
    }
}

// Loop through *all* quoted substrings in the original string.
let str = "\"Rogue One\" is an awesome movie"
pattern.enumerateMatches(in: str, range: str.fullUTF16Range) { (result, flags, stop) in
    // rangeAt(1) is the range representing the characters in the 1st
    // capture group of the regular expression: ([^"]+)
    if let result = result, let range = result.rangeAt(1).toRange() {
        print("This was in quotes: \(str[utf16Range: range] ?? "<bad range>")")
    }
}

答案 3 :(得分:0)

我会使用.components(separatedBy:)

let stringArray = text.components(separatedBy: "\"")

检查stringArray计数是否为&gt; 2(至少有2个引号)。

检查stringArray计数是否为奇数,即计数%2 == 1。

  • 如果是奇数,所有偶数索引都在2个引号之间,它们就是你想要的。
  • 如果是偶数,则所有偶数索引 - 1都在2个引号之间(最后一个没有结束引号)。

这样您还可以捕获多组带引号的字符串,例如: “Rogue One”是一部“星球大战”电影。