一尘不染

快速获取字符串中两个字符串之间的字符串

swift

我从html解析中得到一个字符串,即

string = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);"

我的代码是这样的

var startIndex = text.rangeOfString("'")
var endIndex = text.rangeOfString("',")
var range2 = startIndex2...endIndex
substr= string.substringWithRange(range)

我不确定我的第二个拆分字符串应该是“’”还是“’,”

我希望我的结果是

substr = "Info/99/something"

阅读 268

收藏
2020-07-07

共1个答案

一尘不染

我将使用正则表达式从这样的复杂输入中提取子字符串。

Swift 3.1:

let test = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);"

if let match = test.range(of: "(?<=')[^']+", options: .regularExpression) {
    print(test.substring(with: match))
}

// Prints: Info/99/something

Swift 2.0:

let test = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);"

if let match = test.rangeOfString("(?<=')[^']+", options: .RegularExpressionSearch) {
    print(test.substringWithRange(match))
}

// Prints: Info/99/something
2020-07-07