我从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"
答案 0 :(得分:80)
Swift 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: "',")
答案 1 :(得分:18)
我使用正则表达式从这样的复杂输入中提取子串。
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
答案 2 :(得分:5)
如果始终是第二次拆分,则此方法有效:
let subString = split(string, isSeparator: "'")[1]
答案 3 :(得分:5)
您可以使用var arr = str.componentsSeparatedByString(",")
作为第二个拆分,它会返回数组
答案 4 :(得分:3)
考虑使用正则表达式来匹配单引号之间的所有内容。
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])
答案 5 :(得分:3)
Swift 4.2:
extension String {
//right is the first encountered string after left
func between(_ left: String, _ right: String) -> String? {
guard let leftRange = range(of: left), let rightRange = range(of: right, options: .backwards)
,leftRange.upperBound <= rightRange.lowerBound else { return nil }
let sub = self[leftRange.upperBound...]
let closestToLeftRange = sub.range(of: right)!
return String(sub[..<closestToLeftRange.lowerBound])
}
}
答案 6 :(得分:2)
我改写了Swift 4的最佳答案之一,以了解它与map
有关。我更喜欢使用guard
,IMO
添加向后搜索等选项很容易。
extension String {
func slice(from: String, to: String) -> String? {
guard let rangeFrom = range(of: from)?.upperBound else { return nil }
guard let rangeTo = self[rangeFrom...].range(of: to)?.lowerBound else { return nil }
return String(self[rangeFrom..<rangeTo])
}
}
let test1 = "a[b]c".slice(from: "[", to: "]") // "b"
let test2 = "abc".slice(from: "[", to: "]") // nil
let test3 = "a]b[c".slice(from: "[", to: "]") // nil
let test4 = "[a[b]c]".slice(from: "[", to: "]") // "a[b"
答案 7 :(得分:0)
Swift 4版@litso。查找文本中的所有值
func find(inText text: String, pattern: String) -> [String]? {
do {
let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let result = regex.matches(in: text, options: .init(rawValue: 0), range: NSRange(location: 0, length: text.count))
let matches = result.map { result in
return (text as NSString).substring(with: result.range)
}
return matches
} catch {
print(error)
}
return nil
}
答案 8 :(得分:0)
在Swift 4或更高版本中,您可以在StringProtocol上创建扩展方法以支持子字符串。您可以只返回Substring
而不是新的字符串:
extension StringProtocol where Index == String.Index {
func substring(from start: String, to end: String? = nil, options: String.CompareOptions = []) -> SubSequence? {
guard let lower = range(of: start, options: options)?.upperBound else { return nil }
guard let end = end else { return self[lower...] }
guard let upper = self[lower...].range(of: end, options: options)?.lowerBound else { return nil }
return self[lower..<upper]
}
}
let string = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);"
let substr = string.subString(from: "'") // "Info/99/something', 'City Hall',1, 99);"
let subString = string.subString(from: "'", to: "',") // "Info/99/something"
let subStringCaseInsensitive = string.subString(from: "'info/", to: "/something", options: .caseInsensitive) // "99"
答案 9 :(得分:0)
快捷键5
extension String {
///Returns an empty string when there is no path.
func substring(from left: String, to right: String) -> String {
if let match = range(of: "(?<=\(left))[^\(right)]+", options: .regularExpression) {
return String(self[match])
}
return ""
}
}
答案 10 :(得分:0)
要查找起始字符串和结束字符串之间的所有子字符串:
extension String {
func sliceMultipleTimes(from: String, to: String) -> [String] {
components(separatedBy: from).dropFirst().compactMap { sub in
(sub.range(of: to)?.lowerBound).flatMap { endRange in
String(sub[sub.startIndex ..< endRange])
}
}
}
}
let str = "start A end ... start B end"
str.sliceMultipleTimes(from: "start", to: "end") // ["A", "B"]