5 ms·
I prefer search with an explicit '^' in the pattern to using match. For a throw-away script I'd probably do this: import re is_hex_like = re.compile(r"
by js2 4y ago
I prefer search with an explicit '^' in the pattern to using match. For a throw-away script I'd probably do this:
import re
is_hex_like = re.compile(r"^[a-foi]{6}$", re.I).search
for word in filter(is_hex_like, open("/usr/share/dict/words")):
hexword = word.upper().replace("O", "0").replace("I", "1").rstrip()
print(f"#{hexword}")
- kragen 4y agoThat's nicer than my version! I'm curious why you prefer search(), though.
- js2 4y ago1. I don't have to remember which implicitly anchors to the start of the string and which doesn't. 2. I prefer the explicitness of '^' (maybe that's just another way of stating (1). 3. I can use re.M to modify '^' to match at the start of each line on multiline strings, whereas match will still keep searching from the front. 4. The asymmetry of anchoring the front but not the end is weird. Python now has fullmatch, but ugh, just use the pattern for that if you need it. 5. Off the top of my head, I can't think of another language that has a regex function that implicitly anchors the front.
- kragen 4y agoHmm, I see. Interesting! I think of regexps as state machines, so I think of the implicit loop to find a starting position as extra complexity, which can give rise to for example performance problems, though it's true that in many languages you can't avoid it.
- Too 4y agofindall and multiline mode makes it even easier, at the cost of loading whole file into memory though, for that reason your alternaive is probably better import re wordlist = open("/usr/share/dict/words").read() for word in re.findall(r"^[a-foi]{6}$", wordlist, re.IGNORECASE | re.MULTILINE): hexword = word.upper().replace("O", "0").replace("I", "1") print(f"#{hexword}")