Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find characters inside quotation marks in String

I'm trying to pull out the parts of a string that are in quotation marks, i.e. in "Rouge One" is an awesome movie I want to extract Rouge One.

This is what I have so far but can't figure out where to go from here: I create a copy of the text so that I can remove the first quotation mark so that I can get the index of the second.

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))
}
like image 934
GarySabo Avatar asked Oct 26 '25 02:10

GarySabo


2 Answers

There is no need to create copies or to replace substrings for this task. Here is a possible approach:

  • Use text.range(of: "\"") to find the first quotation mark.
  • Use text.range(of: "\"", range:...) to find the second quotation mark, i.e. the first one after the range found in step 1.
  • Extract the substring between the two ranges.

Example:

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"
}

Another option is a regular expression search with "positive lookbehind" and "positive lookahead" patterns:

if let range = text.range(of: "(?<=\\\").*?(?=\\\")", options: .regularExpression) {
    let stringBetweenQuotes = text.substring(with: range)
    print(stringBetweenQuotes)
}
like image 122
Martin R Avatar answered Oct 29 '25 03:10

Martin R


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

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

separated.dropFirst().first
like image 39
mfaani Avatar answered Oct 29 '25 02:10

mfaani