Python 如何从字符串中提取rgb后面的括号之间的值?
这是我上一篇文章的分支Python 如何从字符串中提取rgb后面的括号之间的值?,python,regex,Python,Regex,这是我上一篇文章的分支 字符串来自我正在解析的一个奇怪的XML文件 我想知道如何使用re从这个字符串中获取rgb值 要稍后使用它们,请执行以下操作: 我将把字符串从左括号拼接到右括号,然后将其列成一个列表。比如: rgb = style[style.find("(") + 1:style.find(")")].split(", ") rgb将是一个列表:['100','2','5']这非常有效,适用于所有情况: impor
- 字符串来自我正在解析的一个奇怪的XML文件
- 我想知道如何使用re从这个字符串中获取rgb值
- 要稍后使用它们,请执行以下操作:
我将把字符串从左括号拼接到右括号,然后将其列成一个列表。比如:
rgb = style[style.find("(") + 1:style.find(")")].split(", ")
rgb将是一个列表:['100','2','5']这非常有效,适用于所有情况:
import re
style = "fill: rgb(100, 2, 5); fill-opacity: 1; font-family: ProjectStocksFont; font-size: 70px; font-weight: normal; font-style: normal; text-decoration: none;"
match = re.search(r'rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)', style)
rgb = match[0].replace("rgb(","").replace(")","").strip().split(',')
这给了你:
rgb[0]
'100'
rgb[1]
'2'
rgb[2]
'5'
然后,您可以将它们转换为整数或任何您需要的值。- 使用或查找字符串中的模式
如果未找到匹配项,则返回空列表.findall
如果未找到匹配项,则返回.search
None
- 模式说明:
- rgb后面的
,捕捉括号之间的任何内容rgb
- 在上测试正则表达式
- rgb后面的
- 用于将数字转换为
重新导入
#串
style=“填充:rgb(100,2,5);填充不透明度:1;字体系列:ProjectStocksFont;字体大小:70px;字体重量:正常;字体样式:正常;文本装饰:无;”
#图案
模式='(?)?
import re
style = "fill: rgb(100, 2, 5); fill-opacity: 1; font-family: ProjectStocksFont; font-size: 70px; font-weight: normal; font-style: normal; text-decoration: none;"
match = re.search(r'rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)', style)
rgb = match[0].replace("rgb(","").replace(")","").strip().split(',')
rgb[0]
'100'
rgb[1]
'2'
rgb[2]
'5'