-3

Is it possible in python to convert a string e.g.

"[A-Z]" to "ABCDE...XYZ"

or

"[0-9]" to "012..9" 

or other similar REs

by using the re python module.

ebart
  • 59
  • 7
  • Why would you use regular expressions for this rather than writing a basic parser? –  Dec 28 '16 at 17:45
  • Because i would like to do this in only one line like new = re.MyExtractor(old) – ebart Dec 28 '16 at 17:47
  • 1
    Why not make a function called `MyExtractor()` ? trying to do what you are doing with `re` isn't a really good solution – MooingRawr Dec 28 '16 at 17:48
  • There's no need to do this in one line. Rethink your design. –  Dec 28 '16 at 17:48
  • Of course, if you only want alpha-numeric ASCII characters, then you can just check which characters match the given pattern. –  Dec 28 '16 at 17:50
  • 3
    AFAIK, `re` is used to pattern match and maybe replace with other patterns. So sure you could define something like replace `A-Z` with `ABC...Z` but then why not just do a parser like what other has suggested. In the end there is no one magical liner you can do that isn't bloated with functions. – MooingRawr Dec 28 '16 at 17:50
  • In regex, `[A-Z]` means any character between `A` and `Z` (any uppercase roman letter,) it does not mean each character between `A` and `Z` in sequence. You definitely do not want to use `re` for this. – 2rs2ts Dec 28 '16 at 17:55
  • 1
    http://stackoverflow.com/a/496603/541038 – Joran Beasley Dec 28 '16 at 17:58

1 Answers1

2

Regular expressions are about matching, not generation.

You can, of course, pre-generate a sequence of all characters you care about and then match your RE against it, selecting only the matching ones.

import re

all_chars = "".join(chr(x) for x in range(32, 128))  # only ASCII here

digits_and_caps_rx = re.compile('([0-9]|[A-Z])')

print "".join(digits_and_caps_rx.findall(all_chars))
9000
  • 39,899
  • 9
  • 66
  • 104