Writing a compiler for a DSL in python

前端 未结 8 1786
囚心锁ツ
囚心锁ツ 2021-02-02 03:51

I am writing a game in python and have decided to create a DSL for the map data files. I know I could write my own parser with regex, but I am wondering if there are existing py

8条回答
  •  -上瘾入骨i
    2021-02-02 04:35

    For "small languages" as the one you are describing, I use a simple split, shlex (mind that the # defines a comment) or regular expressions.

    >>> line = 'SOMETHING: !abc @123 #xyz/123'
    
    >>> line.split()
    ['SOMETHING:', '!abc', '@123', '#xyz/123']
    
    >>> import shlex
    >>> list(shlex.shlex(line))
    ['SOMETHING', ':', '!', 'abc', '@', '123']
    

    The following is an example, as I do not know exactly what you are looking for.

    >>> import re
    >>> result = re.match(r'([A-Z]*): !([a-z]*) @([0-9]*) #([a-z0-9/]*)', line)
    >>> result.groups()
    ('SOMETHING', 'abc', '123', 'xyz/123')
    

提交回复
热议问题