Debian Codegraph @

README.rst

raw
1 ReParser
2 ========
3
4 Simple regex-based lexer/parser for inline markup
5
6 Requirements
7 ------------
8
9 - Python 3
10
11 Usage
12 -----
13
14 Example::
15
16 import re
17 from pprint import pprint
18 from reparser import Parser, Token, MatchGroup
19
20 boundary_chars = r'\s`!()\[\]{{}};:\'".,<>?«»“”‘’*_~='
21 b_left = r'(?:(?<=[' + boundary_chars + r'])|(?<=^))' # Lookbehind
22 b_right = r'(?:(?=[' + boundary_chars + r'])|(?=$))' # Lookahead
23
24 markdown_start = b_left + r'(?<!\\){tag}(?!\s)(?!{tag})'
25 markdown_end = r'(?<!{tag})(?<!\s)(?<!\\){tag}' + b_right
26 markdown_link = r'(?<!\\)\[(?P<link>.+?)\]\((?P<url>.+?)\)'
27 newline = r'\n|\r\n'
28
29 url_proto_regex = re.compile(r'(?i)^[a-z][\w-]+:/{1,3}')
30
31 def markdown(tag):
32 """Return sequence of start and end regex patterns for simple Markdown tag"""
33 return (markdown_start.format(tag=tag), markdown_end.format(tag=tag))
34
35 def url_complete(url):
36 """If URL doesn't start with protocol, prepend it with http://"""
37 return url if url_proto_regex.search(url) else 'http://' + url
38
39 tokens = [
40 Token('bi1', *markdown(r'\*\*\*'), is_bold=True, is_italic=True),
41 Token('bi2', *markdown(r'___'), is_bold=True, is_italic=True),
42 Token('b1', *markdown(r'\*\*'), is_bold=True),
43 Token('b2', *markdown(r'__'), is_bold=True),
44 Token('i1', *markdown(r'\*'), is_italic=True),
45 Token('i2', *markdown(r'_'), is_italic=True),
46 Token('pre3', *markdown(r'```'), skip=True),
47 Token('pre2', *markdown(r'``'), skip=True),
48 Token('pre1', *markdown(r'`'), skip=True),
49 Token('s', *markdown(r'~~'), is_strikethrough=True),
50 Token('u', *markdown(r'=='), is_underline=True),
51 Token('link', markdown_link, text=MatchGroup('link'),
52 link_target=MatchGroup('url', func=url_complete)),
53 Token('br', newline, text='\n', segment_type="LINE_BREAK")
54 ]
55
56 parser = Parser(tokens)
57 text = ('Hello **bold** world!\n'
58 'You can **try *this* awesome** [link](www.eff.org).')
59
60 segments = parser.parse(text)
61 pprint([(segment.text, segment.params) for segment in segments])
62
63 Output::
64
65 [('Hello ', {}),
66 ('bold', {'is_bold': True}),
67 (' world!', {}),
68 ('\n', {'segment_type': 'LINE_BREAK'}),
69 ('You can ', {}),
70 ('try ', {'is_bold': True}),
71 ('this', {'is_bold': True, 'is_italic': True}),
72 (' awesome', {'is_bold': True}),
73 (' ', {}),
74 ('link', {'link_target': 'http://www.eff.org'}),
75 ('.', {})]