问题
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