【问题标题】:Find a String and extract the characters that come after找到一个字符串并提取后面的字符
【发布时间】:2017-04-22 21:55:39
【问题描述】:

用户提交信息后,我正在访问网页的 HTML。

如果我有...

var htmlString = "This is the massive HTML string - it has lots of characters "FindStringDetails"<123789456.123456>  This is a massive HTML string - "
var findString = "FindStringDetails\"<"

有没有合适的方法可以提取“FindStringDetails”之后的数字

【问题讨论】:

    标签: swift string substring


    【解决方案1】:
    import Foundation
    
    var htmlString = "This is the massive HTML string - it has lots of characters \"FindStringDetails\"<123789456.123456>  This is a massive HTML string - "
    var findString = "FindStringDetails\"<"
    
    extension String {
        func matchingStrings(regex: String) -> [[String]] {
            guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
            let nsString = NSString(string: self)
            let results  = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
            return results.map { result in
                (0..<result.numberOfRanges).map { result.range(at: $0).location != NSNotFound
                    ? nsString.substring(with: result.range(at: $0))
                    : ""
                }
            }
        }
    }
    
    let m = htmlString.matchingStrings(regex: "\(findString)(\\d+)\\.(\\d+)")
    
    print(m[0][1]) // 123789456
    print(m[0][2]) // 123456
    

    (代码改编自here。)

    【讨论】:

    • 感谢您的回复。这让我有很多东西要看。如果我试图获取的查询包含数字和数字并且还包含一个空格。 "John3 321" 我该怎么做才能把它变成一个字符串?
    • tuple_cat 已回答您的原始问题。您应该接受问题的答案并提出新问题。
    • 你的意思是像"\(findString)(\\d+) (\\d+)"? (或"\(findString)(\\d+)[\\. ](\\d+)" 匹配两者。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 2023-04-06
    • 2019-11-19
    • 2017-02-25
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多