Skip to content

Instantly share code, notes, and snippets.

@jathanism
Last active December 14, 2015 14:18
Show Gist options
  • Select an option

  • Save jathanism/5099984 to your computer and use it in GitHub Desktop.

Select an option

Save jathanism/5099984 to your computer and use it in GitHub Desktop.
Chainable regex objects.
# 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