2

Hi I want to elegantly expand the substring of the type 4-6 to 4,5,6 in a larger string like

s = "235:2,4,6-9,12,14-19;240:3,5-9,10;245:4,9,10-15,18"

print expand(s)
235:2,4,6,7,8,9,12,14,15,16,17,18,19;240:3,5,6,7,8,9,10;245:4,9,10,11,12,13,14,15,18

Using Python.

Is there some regexp voodoo or similar for this? Thanks a lot!

2
  • 1
    just use "," as delimiter to split string into array and then iterate through array of elements. If there will be "-" contained extract both numbers and insert expended version of given interval. Commented Apr 10, 2013 at 5:43
  • @MartinV.: note that there appear to be two kinds of delimiters. Commented Apr 10, 2013 at 6:58

1 Answer 1

3

You can do:

>>> import re
>>> def repl(match):
...     start, end = match.groups()
...     return ','.join(str(i) for i in range(int(start), int(end)+1))
... 
>>> re.sub(r'(\d+)-(\d+)', repl, "235:2,4,6-9,12,14-19;240:3,5-9,10;245:4,9,10-15,18")
'235:2,4,6,7,8,9,12,14,15,16,17,18,19;240:3,5,6,7,8,9,10;245:4,9,10,11,12,13,14,15,18'

This uses the fact that the repl argument to re.sub can be a callable that takes as argument the match and returns the replacing string.

The expand(s) function would then be:

import re

def repl(match):
    start, end = match.groups()
    return ','.join(str(i) for i in range(int(start), int(end)+1))

def expand(s):
    return re.sub('(\d+)-(\d+)', repl, s)
Sign up to request clarification or add additional context in comments.

2 Comments

You might simplify the function a bit if you put parentheses around the d+ parts of the pattern, then used start, end = match.groups().
Why was this downvoted? I believe it answers exactly the OP's question, so whoever downvoted please give an explanation of you you think this is not only a good solution but completely wrong(as for the FAQ about when to downvote).

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.