Parsing 从Go中的多行输出中提取日期

Parsing 从Go中的多行输出中提取日期,parsing,go,text,Parsing,Go,Text,请参阅下面的netuse命令的输出。现在我想从这段文本中提取到期日期。不幸的是,netuse命令无法输出为json、xml或任何parsble格式。因此,我坚持这段文字:。我只想得到10-6-2017 6:57:20并将其转换为Golang日期格式 问题是:我不知道如何开始?首先查找包含密码过期的行?然后呢 User name jdoe Full Name John Doe Comment User's comment

请参阅下面的netuse命令的输出。现在我想从这段文本中提取到期日期。不幸的是,netuse命令无法输出为json、xml或任何parsble格式。因此,我坚持这段文字:。我只想得到10-6-2017 6:57:20并将其转换为Golang日期格式

问题是:我不知道如何开始?首先查找包含密码过期的行?然后呢

User name                    jdoe
Full Name                    John Doe
Comment
User's comment
Country code                 (null)
Account active               Yes
Account expires              Never

Password last set            1-5-2017 6:57:20
Password expires             10-6-2017 6:57:20
Password changeable          1-5-2017 6:57:20
Password required            Yes
User may change password     Yes
给你:

import (
    "fmt"
    "strings"
)

func main() {
    str := `
User name                    jdoe
Full Name                    John Doe
Comment
User's comment
Country code                 (null)
Account active               Yes
Account expires              Never

Password last set            1-5-2017 6:57:20
Password expires             10-6-2017 6:57:20
Password changeable          1-5-2017 6:57:20
Password required            Yes
User may change password     Yes`

    lines := strings.Split(str, "\n")

    for _, line := range lines {
        if strings.HasPrefix(line, "Password expires") {
            elems := strings.Split(line, " ")
            date := elems[len(elems)-2]
            time := elems[len(elems)-1]
            fmt.Println(date, time)
        }
    }
}

或者,您可以使用regex。

例如,假设dd-mm-yyyy、24小时时钟和阿姆斯特丹当地时间位置

package main

import (
    "bufio"
    "fmt"
    "strings"
    "time"
)

func passwordExpires(netuser string) time.Time {
    const title = "Password expires"
    scanner := bufio.NewScanner(strings.NewReader(netuser))
    for scanner.Scan() {
        line := scanner.Text()
        if !strings.HasPrefix(line, title) {
            continue
        }
        value := strings.TrimSpace(line[len(title):])
        format := "2-1-2006 15:04:05"
        loc := time.Now().Location()
        expires, err := time.ParseInLocation(format, value, loc)
        if err == nil {
            return expires
        }
    }
    return time.Time{}
}

// Europe/Amsterdam
var netuser = `User name                    jdoe
Full Name                    John Doe
Comment
User's comment
Country code                 (null)
Account active               Yes
Account expires              Never

Password last set            1-5-2017 6:57:20
Password expires             10-6-2017 6:57:20
Password changeable          1-5-2017 6:57:20
Password required            Yes
User may change password     Yes`

func main() {
    expires := passwordExpires(netuser)
    fmt.Println(expires)
    if expires.IsZero() {
        fmt.Println("no password expiration")
    }
}
输出:

>go run expire.go
2017-06-10 06:57:20 +0200 CEST