import re input_string="x1,x2,Z3,x4,Z5,x6" re1 = re.compile("(?:x\d(,)?)+") # captures the general thing you want to match using a repeating non-capturing group re2 = re.compile("(x(\d)(,)?)") # your actual matcher def ordered_repl(m): # m is a matchobj buf1 = [] buf2 = [] cap_iter = re.finditer(re2,m.group(0)) # returns an iterator of MatchObjects for all non-overlapping matches for cap_group in cap_iter: capture = cap_group.group(2) # capture the digit buf1.append("X%s" % capture) # buffer X's of this submatch group buf2.append("O%s" % capture) # buffer O's of this submatch group return "%s,%s," % (",".join(buf1),",".join(buf2)) # concatenate the buffers and return print re.sub(re1,ordered_repl,input_string).rstrip(',') # searches string for matches to re1 and passes them to the ordered_repl function
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question