-2

This is branching from my last post here Python get info from long complicated string

  • The string is from a weird XML file I'm parsing

  • I'm wondering how I can use re to get the rgb values from this string

style="fill: rgb(100, 2, 5); fill-opacity: 1; font-family: ProjectStocksFont; font-size: 70px; font-weight: normal; font-style: normal; text-decoration: none;"
  • To use them later like:
print(rgb[0], rgb[1], rgb[2])
# 100 2 5
Trenton McKinney
  • 29,033
  • 18
  • 54
  • 66
Jack Soder
  • 39
  • 5

3 Answers3

1

I would splice the string from the open parenthesis to the close parenthesis, and then make it a list. Something like:

rgb = style[style.find("(") + 1:style.find(")")].split(", ")

rgb will be a list: ['100' , '2' , '5']

Bill
  • 425
  • 2
  • 10
1

This works quite well and fits all situations:

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(',')

Which gives you:

rgb[0]
'100'
rgb[1]
'2'
rgb[2]
'5'

You can then cast them as an integer or whatever you need as well.

Michael Hawkins
  • 2,528
  • 16
  • 29
0
  • Use re.findall or re.searchto find the pattern in the string
    • .findall returns an empty list if no match is found
    • .search returns None if no match is found
  • Pattern explanation:
  • Use map to convert numbers to int
import re

# string
style="fill: rgb(100, 2, 5); fill-opacity: 1; font-family: ProjectStocksFont; font-size: 70px; font-weight: normal; font-style: normal; text-decoration: none;"

# pattern
pattern = '(?<=rgb)\((.+)\)'

rgb = list(map(int, re.findall(pattern, style)[0].split(',')))  # assumes a match will be found.

print(rgb)
[100, 2, 5]

print(rgb[0], rgb[1], rgb[2])
100 2 5

If there's a possibility of no match in the string

# find the pattern
rgb = re.findall(pattern, style)

# if the list isn't empty, extract values as ints
if rgb:  
    rgb = list(map(int, rgb[0].split(',')))
Trenton McKinney
  • 29,033
  • 18
  • 54
  • 66