Skip to content

Simple example

yassir RAMDANI edited this page Sep 14, 2020 · 1 revision

Import SwiLex to use it:

import SwiLex

Define a SwiLaxable enum to list your possible tokens with their corresponding regular expressions:

enum WordNumberTokens: String, SwiLexable {
    static var separators: Set<Character> = [" "]
    
    case text = "[A-Za-z]*"
    case number = "[0-9]*"
}

Then create an instance of SwiLex and call the lex function:

var lexer = SwiLex<WordNumberTokens>()
let tokenList = try lexer.lex(input: "  H3Ll0   W0r 1d  1234 aBcD ")

// returns [text[H], number[3], text[Ll], number[0], text[W], number[0], 
//          text[r], number[1], text[d], number[1234], text[aBcD]]

This will return a list of tokens with the type of the token and its value (the matched string).

Clone this wiki locally