Regexp lexer on Scala

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import scala.util.matching.Regex
class Lexer(val programText : String) {
val ident = "[A-Z]'|[A-Z]"
val text = "\"(.*?)\""
val lparen = "\\("
val rparen = "\\)"
val star = "\\*"
val space = "[ \t\n]+"
val pattern = new Regex("(^"+ident+")|(^"+lparen+")|(^"+rparen+")|(^"+text+")|(^"+star+")|(^"+space+")", "ident", "lparen", "rparen", "text", "txtbuffer", "star", "space")
def analyze() = {
findLexems(programText)
}
def findMatchedGroup(matched: Regex.Match, groupNames: List[String]): String = groupNames match {
case x :: tail if (matched.group(x) != null) => x
case x :: tail => findMatchedGroup(matched, tail)
case _ => ""
}
def findLexems(text : String): List[Lexem] = pattern.findPrefixMatchOf(text) match {
case Some(matched) => {
findMatchedGroup(matched, matched.groupNames.toList) match {
case "ident" => {
val lex = new Lexem(matched toString) with Ident
lex :: findLexems(matched.after toString)
}
case "lparen" => {
val lex = new Lexem(matched toString) with Lparen
lex :: findLexems(matched.after toString)
}
case "rparen" => {
val lex = new Lexem(matched toString) with Rparen
lex :: findLexems(matched.after toString)
}
case "text" => {
val lex = new Lexem(matched toString) with Text
lex :: findLexems(matched.after toString)
}
case "star" => {
val lex = new Lexem(matched toString) with Star
lex :: findLexems(matched.after toString)
}
case "space" => {
text.length match {
case 0 => Nil
case _ => findLexems(matched.after toString)
}
}
}
}
case _ => Nil
}
}