Advertisement
Guest User

Untitled

a guest
Jan 16th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 2.06 KB | None | 0 0
  1. package parser
  2.  
  3. import (
  4.     "regexp"
  5.     "strconv"
  6.     "bytes"
  7. )
  8.  
  9. type Period struct {
  10.     Year   int
  11.     Month  int
  12.     Day    int
  13.     Hour   int
  14.     Minute int
  15.     Second int
  16. }
  17.  
  18. func ParseWithRegexp(s string) Period {
  19.     re := regexp.MustCompile(`P(([\d]+)Y)?(([\d]+)M)?(([\d]+)D)?T(([\d]+)H)?(([\d]+)M)?(([\d]+)S)?`)
  20.     matches := re.FindAllStringSubmatch(s, -1)
  21.  
  22.     return Period{
  23.         Year:   stringToInt(matches[0][2]),
  24.         Month:  stringToInt(matches[0][4]),
  25.         Day:    stringToInt(matches[0][6]),
  26.         Hour:   stringToInt(matches[0][8]),
  27.         Minute: stringToInt(matches[0][10]),
  28.         Second: stringToInt(matches[0][12]),
  29.     }
  30. }
  31.  
  32. func ParseWithoutRegexp(s string) Period {
  33.     p := Period{}
  34.  
  35.     var currentBuffer *bytes.Buffer
  36.  
  37.     isTime := false
  38.  
  39.     for _, c := range s {
  40.         switch {
  41.         case c == 'P':
  42.             currentBuffer = bytes.NewBuffer(nil)
  43.  
  44.         case c == 'T':
  45.             isTime = true
  46.             currentBuffer = bytes.NewBuffer(nil)
  47.  
  48.         case c == 'Y':
  49.             p.Year = stringToInt(currentBuffer.String())
  50.             currentBuffer = bytes.NewBuffer(nil)
  51.  
  52.         case c == 'M' && isTime == false:
  53.             p.Month = stringToInt(currentBuffer.String())
  54.             currentBuffer = bytes.NewBuffer(nil)
  55.  
  56.         case c == 'D':
  57.             p.Day = stringToInt(currentBuffer.String())
  58.             currentBuffer = bytes.NewBuffer(nil)
  59.  
  60.         case c == 'H':
  61.             p.Hour = stringToInt(currentBuffer.String())
  62.             currentBuffer = bytes.NewBuffer(nil)
  63.  
  64.         case c == 'M' && isTime == true:
  65.             p.Minute = stringToInt(currentBuffer.String())
  66.             currentBuffer = bytes.NewBuffer(nil)
  67.  
  68.         case c == 'S':
  69.             p.Second = stringToInt(currentBuffer.String())
  70.             currentBuffer = bytes.NewBuffer(nil)
  71.  
  72.         default:
  73.             currentBuffer.WriteRune(c)
  74.         }
  75.  
  76.     }
  77.  
  78.     return p
  79. }
  80.  
  81. func stringToInt(s string) int {
  82.     if s == "" {
  83.         return 0
  84.     }
  85.     i, _ := strconv.Atoi(s)
  86.     return i
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement