Last active
December 14, 2015 14:18
-
-
Save jathanism/5099984 to your computer and use it in GitHub Desktop.
Chainable regex objects.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # textMonster 1.0.0 | |
| # by Mark Christian | |
| # http://markchristian.org/projects/textmonster | |
| # | |
| # textMonster is licensed under a Creative Commons | |
| # Atttribution 3.0 license: | |
| # http://creativecommons.org/licenses/by/3.0/ | |
| import re | |
| # Main textMonster string class | |
| class textMonster(str): | |
| def textMonster(self, regex): | |
| return textMonsterResult(re.findall(regex, self.__str__())) | |
| return | |
| # textMonster result class | |
| class textMonsterResult: | |
| strings = [] | |
| # Constructor | |
| def __init__(self, strings): | |
| self.strings = strings | |
| # Returns the i'th result | |
| def __getitem__(self, i): | |
| return self.strings[i] | |
| # Returns the number of strings in this result set | |
| def __len__(self): | |
| return len(self.strings) | |
| # Returns the string representation of this result set | |
| def __str__(self): | |
| return self.strings.__str__() | |
| # Executes the given callback once for each string | |
| def each(self, callback): | |
| for string in self.strings: | |
| callback(string) | |
| # Chaining function. Returns a textMonster object with the | |
| # curren result set's strings filtered by the given regex. | |
| def textMonster(self, regex): | |
| results = [] | |
| # Iterate through strings and apply regex to each | |
| for string in self.strings: | |
| results += re.findall(regex, string) | |
| return textMonsterResult(results)% |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment