1

I'm new to python/programing in general and trying to build a statsd to opentsdb proxy based off prometheus' statsd proxy in go. I'm trying to have a string template like the following:

label_name = "${1}_${2}_${3}_${6}"

Then using the above label = string template format, replace the contents of 1,2,3, and 7 with the re.match.groups of a different string. I thought I could do this with strings Template.safe_substitute and a small for loop to turn the groups into a dictionary:

     ...:         label_match_dict = {}
     ...:         for i in range(len(input_match.groups())):
     ...:             label_match_dict[str(i+1)] = input_match.groups()[i]

Yet I am having trouble because it looks like string.Template() is looking for [_a-z][_a-zA-Z0-9] which will not match my dict of {1: "blue", 2: "green", 3: "red", 4: "yellow"}. Now I'm completely lost and feel like there must be a clean way to do this instead of my garden path.

So say I have a statsd metric like:

connstats_by.vip.nested._Common_Domain.89.44.250.117.conncount:40|g

and a regex string like so:

re.compile('connstats_by\\.vip\\.nested\\.([^.]*)\\.([^.]*)\\.([^.]*)\\.([^.]*)\\.([^.]*)\\.([^\:]*)(?:\:)([^\|]*)(?:\|)([^\n]*)')

Which after the above for loop gives me:

{ 1: "_Primary_Domain",
  2: "192",
  3: "168",
  4: "1",
  5: "117",
  6: "conncount",
  7: "40",
  8: "g" }

I just can't seem to wrap my brain around substituting the members of the template with the members of the dict without a really gross looking nested for loop. I feel like I am going down the wrong path. I am hoping someone here can point me toward a more pythonic direction that I can understand 3 months down the road.

Thanks in advance for any help.

1
  • what exactly is your problem Commented May 12, 2018 at 1:10

1 Answer 1

2

Your format string wants a positional list, so this should work:

label_name = "${1}_${2}_${3}_${6}"
metric = "connstats_by.vip.nested._Common_Domain.89.44.250.117.conncount:40|g"
rx = re.compile('connstats_by\\.vip\\.nested\\.([^.]*)\\.([^.]*)\\.([^.]*)\\.([^.]*)\\.([^.]*)\\.([^\:]*)(?:\:)([^\|]*)(?:\|)([^\n]*)')
print(label_name.format(*rx.match(metric).groups()))

Which prints

$89_$44_$250_$40
Sign up to request clarification or add additional context in comments.

1 Comment

Oh snap! Thank you so much that's so much simpler than me doing 3 regex substitutions. Now I just need to remove the dollar sign which is nothing. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.