captures.nim 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import unittest, optional_nonstrict
  2. include nre
  3. block: # captures
  4. block: # map capture names to numbers
  5. check(getNameToNumberTable(re("(?<v1>1(?<v2>2(?<v3>3))(?'v4'4))()")) ==
  6. { "v1" : 0, "v2" : 1, "v3" : 2, "v4" : 3 }.toTable())
  7. block: # capture bounds are correct
  8. let ex1 = re("([0-9])")
  9. check("1 23".find(ex1).matchBounds == 0 .. 0)
  10. check("1 23".find(ex1).captureBounds[0] == 0 .. 0)
  11. check("1 23".find(ex1, 1).matchBounds == 2 .. 2)
  12. check("1 23".find(ex1, 3).matchBounds == 3 .. 3)
  13. let ex2 = re("()()()()()()()()()()([0-9])")
  14. check("824".find(ex2).captureBounds[0] == 0 .. -1)
  15. check("824".find(ex2).captureBounds[10] == 0 .. 0)
  16. let ex3 = re("([0-9]+)")
  17. check("824".find(ex3).captureBounds[0] == 0 .. 2)
  18. block: # named captures
  19. let ex1 = "foobar".find(re("(?<foo>foo)(?<bar>bar)"))
  20. check(ex1.captures["foo"] == "foo")
  21. check(ex1.captures["bar"] == "bar")
  22. let ex2 = "foo".find(re("(?<foo>foo)(?<bar>bar)?"))
  23. check("foo" in ex2.captureBounds)
  24. check(ex2.captures["foo"] == "foo")
  25. check(not ("bar" in ex2.captures))
  26. expect KeyError:
  27. discard ex2.captures["bar"]
  28. block: # named capture bounds
  29. let ex1 = "foo".find(re("(?<foo>foo)(?<bar>bar)?"))
  30. check("foo" in ex1.captureBounds)
  31. check(ex1.captureBounds["foo"] == 0..2)
  32. check(not ("bar" in ex1.captures))
  33. expect KeyError:
  34. discard ex1.captures["bar"]
  35. block: # capture count
  36. let ex1 = re("(?<foo>foo)(?<bar>bar)?")
  37. check(ex1.captureCount == 2)
  38. check(ex1.captureNameId == {"foo" : 0, "bar" : 1}.toTable())
  39. block: # named capture table
  40. let ex1 = "foo".find(re("(?<foo>foo)(?<bar>bar)?"))
  41. check(ex1.captures.toTable == {"foo" : "foo"}.toTable())
  42. check(ex1.captureBounds.toTable == {"foo" : 0..2}.toTable())
  43. let ex2 = "foobar".find(re("(?<foo>foo)(?<bar>bar)?"))
  44. check(ex2.captures.toTable == {"foo" : "foo", "bar" : "bar"}.toTable())
  45. block: # capture sequence
  46. let ex1 = "foo".find(re("(?<foo>foo)(?<bar>bar)?"))
  47. check(ex1.captures.toSeq == @[some("foo"), none(string)])
  48. check(ex1.captureBounds.toSeq == @[some(0..2), none(Slice[int])])
  49. check(ex1.captures.toSeq(some("")) == @[some("foo"), some("")])
  50. let ex2 = "foobar".find(re("(?<foo>foo)(?<bar>bar)?"))
  51. check(ex2.captures.toSeq == @[some("foo"), some("bar")])