从字符串中提取RGB值

时间:2017-12-05 19:19:19

标签: ios swift rgb

如何从以下字符串中提取RBG值?:

"rgb(230, 0, 0)"

我想从background-color值中获取提取let range = string.range(of: "\"background-color: ") let startPoint = range.location + range.length let subString = string.substring(from: startPoint) //generating error claiming 'cannot convert value of type 'int' to expected argument type 'string.index'. //paused here to ask S.O b/c I do not think substrings is the best way to do this, maybe there is a library that extracts values from html elements, or regex? ,因此我可以将其转换为十六进制字符串并更新一些UI。

{{1}}

2 个答案:

答案 0 :(得分:2)

您可以使用regex来获取两个字符串之间的字符串:

let string = "<span style=\"background-color: rgb(230, 0, 0);\">"

let pattern = "(?<=background-color: )(.*)(?=;)"
if let rgb = string.range(of: pattern, options: .regularExpression).map({String(string[$0])}) {
    print(rgb)  // "rgb(230, 0, 0)"
}

答案 1 :(得分:0)

let range = (string as NSString).range(of: "\"background-color: ")
let startPoint = range.location + range.length
let subString = (string as NSString).substring(from: startPoint)
let deliminator = ";"
let components = subString.components(separatedBy: deliminator)
let rgb = components[0]

print(rgb) -> "rgb(230, 0, 0)"