Swift获取string中的两个string之间的string
我得到一个string从HTMLparsing是,
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)
我不确定我的第二个拆分string是“”还是“”,“
我想要我的结果
substr = "Info/99/something"
我会使用正则expression式从这样的复杂input中提取子string。
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
斯威夫特4
extension String { func slice(from: String, to: String) -> String? { return (range(of: from)?.upperBound).flatMap { substringFrom in (range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in String(self[substringFrom..<substringTo]) } } } }
Swift 3
extension String { func slice(from: String, to: String) -> String? { return (range(of: from)?.upperBound).flatMap { substringFrom in (range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in substring(with: substringFrom..<substringTo) } } } }
老答案:
import Foundation extension String { func sliceFrom(start: String, to: String) -> String? { return (rangeOfString(start)?.endIndex).flatMap { sInd in (rangeOfString(to, range: sInd..<endIndex)?.startIndex).map { eInd in substringWithRange(sInd..<eInd) } } } } "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);" .sliceFrom("'", to: "',")
如果它总是第二次分裂,这将工作:
let subString = split(string, isSeparator: "'")[1]
你可以使用var arr = str.componentsSeparatedByString(",")
作为你的第二个分裂,这将返回你的数组
考虑使用正则expression式来匹配单引号之间的所有内容。
let string = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);" let pattern = "'(.+?)'" let regex = NSRegularExpression(pattern: pattern, options: nil, error: nil) let results = regex!.matchesInString(string, options: nil, range: NSMakeRange(0, count(string))) as! [NSTextCheckingResult] let nsstring = string as NSString let matches = results.map { result in return nsstring.substringWithRange(result.range)} // First match println(matches[0])