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

2020/12/12 00:41 · ios ·  · 0评论

我从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"

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

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
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])
            }
        }
    }
}

"javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);"
  .sliceFrom("'", to: "',")

我改写了Swift的最高答案之一,以了解它在做什么map我更喜欢使用guardIMO的版本

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"

您可以将其var arr = str.componentsSeparatedByString(",")用作第二个拆分,它将返回数组

如果始终是第二个拆分,则此方法有效:

let subString = split(string, isSeparator: "'")[1]

考虑使用正则表达式来匹配单引号之间的所有内容。

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])

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])
    }

}

在Swift 4或更高版本中,您可以在StringProtocol上创建扩展方法以支持子字符串。您可以返回aSubstring而不是新的String:

编辑/ u [日期:Swift 5

extension StringProtocol  {
    func substring<S: StringProtocol>(from start: S, options: String.CompareOptions = []) -> SubSequence? {
        guard let lower = range(of: start, options: options)?.upperBound
        else { return nil }
        return self[lower...]
    }
    func substring<S: StringProtocol, T: StringProtocol>(from start: S, to end: T, options: String.CompareOptions = []) -> SubSequence? {
        guard let lower = range(of: start, options: options)?.upperBound,
            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"

@litso的Swift 4版本。查找文本中的所有值

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
}

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

查找起始字符串和结束字符串之间的所有子字符串:

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"]
本文地址:http://ios.askforanswer.com/kuaisuhuoquzifuchuanzhonglianggezifuchuanzhijiandezifuchuan.html
文章标签: ,   ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!