tokenize any text stream given some basic regex rules to match tokens
NOTE This library works well, but I don't use it anymore. I just use
while loops in a state machine pattern to tokenize. No library needed (or wanted). Here are some examples: one, two Yes it's stateful and verbose, but in my experience this is easier to write and maintain (using TDD of course). Just setup a test-runner and start small then grow it to tokenize everything you want. Once you get the hang of it, it's really easy to figure out how to tokenize something since you have full control of the state machine.
var tokenizer2 = ;//create a readable/writeable streamvar token_stream = ;//make some rulestoken_stream;token_stream;token_stream;token_stream;//write some info to the consoletoken_stream;token_stream;//pipe in some datafs;
print "some multi-lined string"123.25 times -10
token: type: 'symbol' src: 'print' line: 1 col: 1token: type: 'whitespace' src: ' ' line: 1 col: 6token: type: 'string' src: '"some multi-\nlined string"' line: 1 col: 7token: type: 'whitespace' src: '\n\n' line: 2 col: 14token: type: 'number' src: '123.25' line: 4 col: 1token: type: 'whitespace' src: ' ' line: 4 col: 7token: type: 'symbol' src: 'times' line: 4 col: 8token: type: 'whitespace' src: ' ' line: 4 col: 13token: type: 'number' src: '-10' line: 4 col: 14token: type: 'whitespace' src: '\n' line: 4 col: 17DONE
What if more than one rule matches a token?
token_stream.addRule adds rules in an order sensitive way. The first matching rule will be used.
The key difference between this and tokenizer is the way it matches rules.
tokenizer uses disect to do bisection on a chunk of text. This is a fast approach, however doesn't work well if your regex rule expects some specific characters at the end of the token. To solve this tokenizer2 simply starts at the beginning of the chunk, and finds the longest matching rule.
- tokenizer2 wraps through2.obj so all the node stream APIs should work nicely
- tokenizer2 uses the standard
'data'event to emit the tokens
- tokenizer2 emits line and col numbers
Non-streaming, synchronous API
If, for whatever reason, you don't want to use the streaming api. There is a lighter weight, synchronous api.
var core = ;var t =;//add rules just like the streaming apit;//Give it strings to tokenizet;t;//Call this when it's donet;//this may throw an error