从字符串中提取 RGB 值 [英] Extracting the RGB value from a string
本文介绍了从字符串中提取 RGB 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从以下字符串中提取 RBG 值?:
How would I extract the RBG value from the following string?:
let string = "
我想从 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?
推荐答案
您可以使用 regex 来获取字符串两个字符串之间:
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)"
}
这篇关于从字符串中提取 RGB 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文