Skip to content

Commit

Permalink
add example as test case
Browse files Browse the repository at this point in the history
  • Loading branch information
leonfuss committed Oct 30, 2024
1 parent 16c68f2 commit aab54e3
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 21 deletions.
2 changes: 2 additions & 0 deletions examples/stdlib/string/regex.check
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ ab
cd
(0, 2)
(3, 5)
matched: Hello 123 range: (0, 9)
matched: World 456 range: (10, 19)
25 changes: 12 additions & 13 deletions examples/stdlib/string/regex.effekt
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,10 @@ def printIndices(m: Option[Match]) = printSome(m) { it =>
}

def printGroups(m: Option[Match]) = printSome(m) { it =>
it.groups.map { g => g.matched() }.join("\n")
it.groups.map { g => g.matched }.join("\n")
}

def printGroupIndices(m: Option[Match]) = {
def show(it: Option[Range]): String = {
it match {
case Some(r) => r.show()
case None() => "None"
}
}
printSome(m) { it =>
it.groups.map { g => g.index().show() }.join("\n")
}
Expand All @@ -52,16 +46,21 @@ def main() = {
rgx3.exec(src).printIndices()

// capture groups
val rgx4 = regex("(\\w+) (\\w+)", [GenerateIndices()])
val rgx4 = regex("(\\w+) (\\w+)")
val m1 = rgx4.exec(src)
m1.printMatched()
m1.printGroups()
m1.printGroupIndices()







// example ussage
val rx = regex("(\\w+)\\s(\\d+)", [Global()])
val text = "Hello 123 World 456"
loop { {l} =>
exec(rx, text) match {
case Some(m) =>
println("matched: " ++ m.matched ++ " range: (" ++ m.start.show() ++ ", " ++ m.end.show() ++ ")")
case None() => l.break()
}
}
}
17 changes: 9 additions & 8 deletions libraries/js/text/regex.effekt
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,14 @@ def regex(pattern: String, flags: List[RegexFlags]): Regex = {
*
* Example usage:
* ```effekt
* val rx = regex("(\\w+)\\s(\\d+)", "g")
* val rx = regex("(\\w+)\\s(\\d+)", [Global()])
* val text = "Hello 123 World 456"
* while (true) {
* exec(rx, text) match = {
* Some(m) =>
* println("matched: " ++ m.matched ++ "range: " ++ m.start.show() ++ ", " ++ m.end.show()))
* None() => break
* loop { {l} =>
* exec(rx, text) match {
* case Some(m) =>
* println("matched: " ++ m.matched ++ " range: (" ++ m.start.show() ++ ", " ++ m.end.show() ++ ")")
* case None() => l.break()
* }
* }
* ```
*/
Expand Down Expand Up @@ -145,7 +146,7 @@ function regex$exec(reg, str) {
matched: match[i],
start: match.indices[i][0],
end: match.indices[i][1]
}
})
} else {
// Push an empty string if an intermediate group is undefined
groups.push({matched: ""});}
Expand Down Expand Up @@ -179,7 +180,7 @@ def show(m: Match): String = {
}

def show(g: Group): String = {
val range = g.index.show{ it => show(it) }
val range = g.index.show()

g.matched ++ "\nfrom: " ++ range
}
Expand Down

0 comments on commit aab54e3

Please sign in to comment.