1
import re
pattern = re.compile(r"(\d{3})+$")
print pattern.match("123567").groups()

output result:

('567',)

I need the result is ('123','567'). The (\d{3}) only can output last group, but I want output every group.

lens
  • 133
  • 1
  • 11

1 Answers1

2

I am doing it in a bit of pythonic way

Solution 1

Python Code

p = re.compile(r'(?<=\d)(?=(?:\d{3})+$)')
test_str = "2890191245"
tmp = [x.start() for x in re.finditer(p, test_str)]
res = [test_str[0: tmp[0]]] + [(test_str[tmp[i]: tmp[i] + 3]) for i in range(len(tmp))]

Ideone Demo

Solution 2 (one liner)

print(re.sub("(?<=\d)(?=(\d{3})+$)", ",", test_str).split(","))

Ideone Demo

rock321987
  • 10,942
  • 1
  • 30
  • 43
  • The answer is right, but I don't understand `p = re.compile(r'(\d{3})')`. Could you explain it ? – lens Apr 29 '16 at 03:36
  • Yes! However the OP has still not answered what would be the expected output in case of `"1235678"`. – AKS Apr 29 '16 at 03:36
  • @user5673769 its same as you mentioned in your regex except this is finding all the _non-overlapping_ combination of three digits present in the string – rock321987 Apr 29 '16 at 03:38
  • @AKS I think what you are implying is to also find overlapping patterns..is it that? – rock321987 Apr 29 '16 at 03:40
  • Not exactly what I am thinking that does the OP want the result to be `[123, 567, 8]` or just `[123, 567]`. – AKS Apr 29 '16 at 03:41
  • 1
    @AKS `8` is not a 3 digit string so shouldn't be there. – Ozgur Vatansever Apr 29 '16 at 03:42
  • @AKS maybe..but OP is asking for exact three digits – rock321987 Apr 29 '16 at 03:42
  • @ozgur yes I know that. I am just trying to get a sense of the expected output when this condition occurs. But it seems OP does want groups of 3 digits from start leaving the remainders. – AKS Apr 29 '16 at 03:45
  • @rock321987 your answer can solve `123456`,but cannot solve `2389019`. When the `s=2389019`, the answer is `None`. I want the answer is [2,389,019]. – lens Apr 29 '16 at 03:46
  • @ozgur do you see in the comment above 2 is also not a 3 digit string and the output OP is expecting is totally different. – AKS Apr 29 '16 at 03:48
  • 1
    @rock321987 That's great. However I have this feeling that OP is after something like this: https://docs.python.org/dev/whatsnew/2.7.html#pep-378-format-specifier-for-thousands-separator – AKS Apr 29 '16 at 06:32
  • @AKS actually my regex was inspired from Mastering Regular Expression which was doing exact same thing as mentioned in the link but only using regex replace – rock321987 Apr 29 '16 at 06:34
  • 1
    @rock321987 The question is similar with AKS, but I hope I can find a easy solution way and I think regular expression is powerful. And I think using regular expression dealing with question about string is more convenience than using other tools.Thank you spending time solve this question. – lens Apr 29 '16 at 08:34