namepattern.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package stringutils2
  15. import (
  16. "fmt"
  17. "strconv"
  18. "strings"
  19. )
  20. const RepChar = '#'
  21. const RandomChar = '?'
  22. // name##
  23. // name##9#
  24. func ParseNamePattern2(name string) (string, string, int, int, byte) {
  25. var match string
  26. var pattern string
  27. var patternLen int
  28. var offset int
  29. var charType byte
  30. start := strings.IndexByte(name, RepChar)
  31. if start >= 0 {
  32. end := start + 1
  33. for end < len(name) && name[end] == RepChar {
  34. end += 1
  35. }
  36. patternLen = end - start
  37. nend := strings.IndexByte(name[end:], RepChar)
  38. if nend > 0 {
  39. if oi, err := strconv.ParseInt(name[end:end+nend], 10, 64); err == nil {
  40. offset = int(oi)
  41. }
  42. end = end + nend + 1
  43. }
  44. match = fmt.Sprintf("%s%%%s", name[:start], name[end:])
  45. pattern = fmt.Sprintf("%s%%0%dd%s", name[:start], patternLen, name[end:])
  46. charType = RepChar
  47. } else {
  48. start := strings.IndexByte(name, RandomChar)
  49. if start >= 0 {
  50. end := start + 1
  51. for end < len(name) && name[end] == RandomChar {
  52. end += 1
  53. }
  54. patternLen = end - start
  55. match = fmt.Sprintf("%s%%%s", name[:start], name[end:])
  56. pattern = fmt.Sprintf("%s%%s%s", name[:start], name[end:])
  57. charType = RandomChar
  58. } else {
  59. match = fmt.Sprintf("%s-%%", name)
  60. pattern = fmt.Sprintf("%s-%%d", name)
  61. }
  62. }
  63. return match, pattern, patternLen, offset, charType
  64. }