Regular expression generalization for arbitrary objects

Regular expression libraries usually work with strings (e.g. remodule in Python). However, the idea of ​​regular expressions can be easily extended to work with arbitrary objects. All you need from objects is equality.

Are there libraries (especially in Python) that allow you to use regular expressions for sequences of arbitrary objects instead of characters? Or maybe there is some kind of dirty hack that allows you to use regular expression libraries for non-strings?

+4
source share
2 answers

, , Haskell. ( Prolog , , Prolog unification, , ).

Python ( ):

+5

... , , .

, Action ActionList, ... .

import re

class Action(object):
  def __str__(self):
    return self.re

class Jump(Action):
  re = "J"
class Run(Action):
  re = "R"

class ActionList(list):
  def __init__(self, *args):
    super(ActionList, self).__init__(self)
    for i in args:
      self.append(i)
  def re_search(self,regex):
     s = "".join(str(i) for i in self)
     return re.search(regex,s)

al = ActionList(Jump(),Run(),Jump(),Jump())

:

type(al[al.re_search("JJ").pos])

3:

<class '__main__.Jump'>

:

al.re_search("R.R")

.

+1

Source: https://habr.com/ru/post/1570218/


All Articles