Commits

anatoly techtonik  committed 5b8d8f7

Add helper to create regexp-based rules

  • Participants
  • Parent commits d0c9227

Comments (0)

Files changed (1)

 
 import re
 
-# just an example
+# just an example of simple rule
 def rule_linkstub(text):
   """ replace urls with [link] stubs """
   linkre = re.compile('https?://\S+')
     return None
   return (text[:match.start()], "[link]", text[match.end():])
 
+
+# helper to substitute backreferences
+def subst_backrefs(pattern, groups):
+  """ helper to replace backreferences such as \0, \1
+      in the given `pattern` string with elements from
+      the `groups` tuple
+  """
+  backrefs = re.findall(r'\\\d{1,2}', pattern)
+  for b in backrefs:
+    pattern = pattern.replace(b, groups[int(b[1:])])
+  return pattern
+
+
+# helper to build regexp based rules
+def create_regexp_rule(search, replace=r'\0'):
+  """ helper that returns rule, suitable as an argument to
+      wikify. parameters are regexps - what to `search` for
+      and what to `replace` with. it is possible to use
+      backreferences (like \1) in replacement string.
+  """
+  search = re.compile(search)
+
+  def regexp_rule(text):
+      # saving for debug
+      _research = search
+      _replace = replace
+
+      match = _research.search(text)
+      if match == None:
+        return None
+
+      # match.groups() doesn't return whole match as a 1st element
+      groups = (match.group(0),) + match.groups()
+      replaced = subst_backrefs(_replace, groups)
+
+      return (text[:match.start()], replaced, text[match.end():])
+
+  return regexp_rule
+
 # [ ] sets of common rules
 # [ ] configurable replacements
 
 
   text = ''
   print(wikify(text, [rule_linkstub]))
+
+  text = 'somematch metext'
+  print text
+  w = create_regexp_rule('match me', ' replacement (\\0) ')
+  print wikify(text, [w])
+