regexp_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. package parser
  2. import (
  3. "regexp"
  4. "testing"
  5. )
  6. func TestRegExp(t *testing.T) {
  7. tt(t, func() {
  8. {
  9. // err
  10. test := func(input string, expect interface{}) {
  11. _, err := TransformRegExp(input)
  12. is(err, expect)
  13. }
  14. test("[", "Unterminated character class")
  15. test("(", "Unterminated group")
  16. test("\\(?=)", "Unmatched ')'")
  17. test(")", "Unmatched ')'")
  18. }
  19. {
  20. // err
  21. test := func(input, expect string, expectErr interface{}) {
  22. output, err := TransformRegExp(input)
  23. is(output, expect)
  24. is(err, expectErr)
  25. }
  26. test(")", "", "Unmatched ')'")
  27. test("\\0", "\\0", nil)
  28. test("0:(?)", "", "Invalid group")
  29. test("(?)", "", "Invalid group")
  30. test("(?U)", "", "Invalid group")
  31. test("(?)|(?i)", "", "Invalid group")
  32. test("(?P<w>)(?P<w>)(?P<D>)", "", "Invalid group")
  33. }
  34. {
  35. // err
  36. test := func(input string, expect string) {
  37. result, err := TransformRegExp(input)
  38. is(err, nil)
  39. is(result, expect)
  40. _, err = regexp.Compile(result)
  41. is(err, nil)
  42. }
  43. testErr := func(input string, expectErr string) {
  44. _, err := TransformRegExp(input)
  45. is(err, expectErr)
  46. }
  47. test("", "")
  48. test("abc", "abc")
  49. test(`\abc`, `abc`)
  50. test(`\a\b\c`, `a\bc`)
  51. test(`\x`, `x`)
  52. test(`\c`, `c`)
  53. test(`\cA`, `\x01`)
  54. test(`\cz`, `\x1a`)
  55. test(`\ca`, `\x01`)
  56. test(`\cj`, `\x0a`)
  57. test(`\ck`, `\x0b`)
  58. test(`\+`, `\+`)
  59. test(`[\b]`, `[\x08]`)
  60. test(`\u0z01\x\undefined`, `u0z01xundefined`)
  61. test(`\\|'|\r|\n|\t|\u2028|\u2029`, `\\|'|\r|\n|\t|\x{2028}|\x{2029}`)
  62. test("]", "]")
  63. test("}", "}")
  64. test("%", "%")
  65. test("(%)", "(%)")
  66. test("(?:[%\\s])", "(?:[%"+WhitespaceChars+"])")
  67. test("[[]", "[[]")
  68. test("\\101", "\\x41")
  69. test("\\51", "\\x29")
  70. test("\\051", "\\x29")
  71. test("\\175", "\\x7d")
  72. test("\\04", "\\x04")
  73. testErr(`<%([\s\S]+?)%>`, "S in class")
  74. test(`(.)^`, "([^\\r\\n])^")
  75. test(`\$`, `\$`)
  76. test(`[G-b]`, `[G-b]`)
  77. test(`[G-b\0]`, `[G-b\0]`)
  78. }
  79. })
  80. }
  81. func TestTransformRegExp(t *testing.T) {
  82. tt(t, func() {
  83. pattern, err := TransformRegExp(`\s+abc\s+`)
  84. is(err, nil)
  85. is(pattern, `[`+WhitespaceChars+`]+abc[`+WhitespaceChars+`]+`)
  86. is(regexp.MustCompile(pattern).MatchString("\t abc def"), true)
  87. })
  88. }