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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
package main
import (
"fmt"
"regexp"
"strings"
)
func test_regex(in string, out []string, trimAndDeleteQuotes bool) {
err_found := false
// ********************************
// Parse
//re := regexp.MustCompile(`"[^(\\")]*"\s*`)
//re := regexp.MustCompile(`[^\s]+\s*`)
re := regexp.MustCompile(`("[^(\\")]*"\s*)|([^\s]+\s*)`)
result := re.FindAllString(in, -1)
if trimAndDeleteQuotes {
for i, str := range result {
str = strings.TrimSpace(str)
if len(str) > 0 {
if str[0] == '"' {
str = str[1:]
if len(str) > 0 {
if str[len(str)-1] == '"' {
if (len(str) < 2) || (str[len(str)-2] != '\\') {
str = str[:len(str)-1]
}
}
}
}
}
str = strings.Replace(str, "\\\"", "\"", -1)
result[i] = str
}
}
// ********************************
// Check
fmt.Printf("test_regex '%s' : ", in)
for i, str := range result {
fmt.Printf(" '%s'", str)
if i < len(out) {
if out[i] == str {
//fmt.Printf("[OK]")
} else {
fmt.Printf("[ERR]")
err_found = true
}
} else {
fmt.Printf("[ERR_TOO_MANY_ELEMENTS]")
err_found = true
}
}
if len(result) < len(out) {
fmt.Printf("'%s'[ERR_NOT_FOUND]", out[len(result)])
err_found = true
}
if err_found {
fmt.Printf(" => result [ERR]\n")
} else {
fmt.Printf(" => result [OK]\n")
}
}
func test_regexAll() {
fmt.Printf("***** trimAndDeleteQuotes : FALSE ******\n")
trimAndDeleteQuotes := false
test_regex("a bbb ccc d eee", []string{"a ", "bbb ", "ccc ", "d ", "eee"}, trimAndDeleteQuotes)
test_regex("\"a\" \"b b\" \"ccc\" \"d \" \"eee\"", []string{"\"a\" ", "\"b b\" ", "\"ccc\" ", "\"d \" ", "\"eee\""}, trimAndDeleteQuotes)
test_regex("a b \"c c\" d e", []string{"a ", "b ", "\"c c\" ", "d ", "e"}, trimAndDeleteQuotes)
test_regex("aaa \"b\\\"b\" ccc", []string{"aaa ", "\"b\\\"b\" ", "ccc"}, trimAndDeleteQuotes)
test_regex("a b \"c \\\" c\" d e", []string{"a ", "b ", "\"c \\\" c\" ", "d ", "e"}, trimAndDeleteQuotes)
fmt.Printf("\n***** trimAndDeleteQuotes : TRUE ******\n")
trimAndDeleteQuotes = true
test_regex("a bbb ccc d eee", []string{"a", "bbb", "ccc", "d", "eee"}, trimAndDeleteQuotes)
test_regex("\"a\" \"b b\" \"ccc\" \"d \" \"eee\"", []string{"a", "b b", "ccc", "d ", "eee"}, trimAndDeleteQuotes)
test_regex("a b \"c c\" d e", []string{"a", "b", "c c", "d", "e"}, trimAndDeleteQuotes)
test_regex("aaa \"b\\\"b\" ccc", []string{"aaa", "b\"b", "ccc"}, trimAndDeleteQuotes)
test_regex("a b \"c \\\" c\" d e", []string{"a", "b", "c \" c", "d", "e"}, trimAndDeleteQuotes)
} |
Partager