Last active
April 24, 2020 03:31
-
-
Save nirlanka/04e0c8d63fd2ec2cbbaae322b7f826c3 to your computer and use it in GitHub Desktop.
Simple tokenizer examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
`<div> | |
Some text here | |
<div> | |
<h3>Lorem <a href="./abc/def.html">ipsum</a></h3> | |
<p>Dolor sit</p> | |
<p>amet</p> | |
</div>` | |
.split(/([<>\s="\/]{1})/g) | |
.map(s=>s.trim()) | |
.filter(Boolean) | |
/* | |
Result: | |
["<", "div", ">", "Some", "text", "here", "<", "div", ">", "<", | |
"h3", ">", "Lorem", "<", "a", "href", "=", """, ".", "/", "abc", | |
"/", "def.html", """, ">", "ipsum", "<", "/", "a", ">", "<", "/", | |
"h3", ">", "<", "p", ">", "Dolor", "sit", "<", "/", "p", ">", "<", | |
"p", ">", "amet", "<", "/", "p", ">", "<", "/", "div", ">"] | |
*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
`pkg bar { | |
func foo() { | |
a = 1; | |
d = false; #lorem ipsum# | |
e = { | |
x: 1.35, #dolor sit# | |
y: 2.2, | |
f: "\"to\"" | |
} | |
}; | |
b = "abc"; | |
c = foo(); | |
}` | |
.split(/([\s\(\)\{\}=;"\.\,#]{1})/g) | |
.map(s=>s.trim()) | |
.filter(Boolean); | |
/* | |
Result: | |
["pkg", "bar", "{", "func", "foo", "(", ")", "{", | |
"a", "=", "1", ";", "d", "=", "false", ";", "#", | |
"lorem", "ipsum", "#", "e", "=", "{", "x:", "1", | |
".", "35", ",", "#", "dolor", "sit", "#", "y:", | |
"2", ".", "2", ",", "f:", """, "\", """, "to", | |
"\", """, """, "}", "}", ";", "b", "=", """, | |
"abc", """, ";", "c", "=", "foo", "(", ")", ";", | |
"}"] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Known issue 1: Multiple spaces and line-breaks inside strings are lost.
Possible solution/idea: Removing the
.map(s=>s.trim())
operation will keep all spaces, and spaces will be available with context.