Extracting the RGB value from a string

瘦欲@ 提交于 2020-01-14 06:56:50

问题


How would I extract the RBG value from the following string?:

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

I would like to get extract "rgb(230, 0, 0)" from the background-color value, so I can convert it to a hex string and update some UI.

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?

回答1:


You can use a regex to get the string between two strings:

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



回答2:


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


来源:https://stackoverflow.com/questions/47661106/extracting-the-rgb-value-from-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!