3 ms·
I think it's the re package's fault. It's badly designed. re.match should return a match object no matter what, and .group() should return strings, empty strin
by est 8y ago
I think it's the re package's fault. It's badly designed.
re.match should return a match object no matter what, and .group() should return strings, empty string if non were matched.
We don't even need anything remotely :=
- yorwba 8y agoWhat about regular expressions that match the empty string? There might be ways the regular expression library could be designed better, but making re.match return a match when there's no match is not an improvement.
- PurpleRamen 8y agoNo match is also a match. The problem here is that it's bad design design if a function returns multiple different types of result. Generally there should only be one type of result to make handling reliable. It if's neccessary, you can still test for an empty result, making it the optional case that it is.
- est 8y agoand what's the use case for that? The main problem here is that you can't chain re.match().group() because None has no .group() Why do you want to match empty string with a group?
- yorwba 8y agoThe use case for a regular expression that matches the empty string is detecting whether something starts with an optional pattern. E.g. '(foo)?' to match the optional prefix 'foo'. FWIW if you really want re.match().group() to always return a string, you can just wrap all your regular expressions with '(...)?'. The reason why someone might want to be able to distinguish between "no match" and "the match is empty" is writing code that takes any arbitrary regular expression and uses it as a filter. Then someone else could pass in an expression that matches empty and everything works together nicely.
- sirk390 8y agoDo you have any arguments to justify that? It sound very reasonable to only return a match object when you have a match. Otherwise, you give more responsability to the Match class (knowing when it is None and handling many special cases) while you could just use None.