【问题标题】:How do I separate the control sequence from input string如何将控制序列与输入字符串分开
【发布时间】:2016-08-26 23:09:40
【问题描述】:

我有一个示例程序可以在我的终端上接受密码,为此我正在使用终端包。但是,当我在输入密码时误按任何箭头键时,会出现一些奇怪的错误。

我想将我的输入密码分开,然后仅将其用于授权。以下是我尝试过的。

我的输入字符串是

// Accept password using terminal.ReadPassword() which returns []byte
// password entered is "\x1b[Aabcd"
// where \x1b[A is the up arrow key and abcd is my input entry. 

for _, c := range bytes.Runes(password) {
                if !unicode.IsPrint(c) {
                    fmt.Printf("\nINVALID PWD ")
                } else {
                    d = append(d, c)
                }
            }
fmt.Println("\n\n", fmt.Sprintf("%c", d))

这里最后打印[Aabcd

无论如何我只能在没有 [A here 的情况下捕获/打印输入字符吗?

谢谢

【问题讨论】:

    标签: go


    【解决方案1】:

    1- 如果您需要将控制序列与输入字符串分开,您可以使用unicode.IsControl(r)

    IsControl 报告符文是否是控制字符。 C (其他)Unicode 类别包括更多的代码点,例如 代理人;使用 Is(C, r) 来测试它们。

    2- 另见:getpasswd functionality in Go?

    package main
    
    import "fmt"
    import "github.com/howeyc/gopass"
    
    func main() {
        fmt.Printf("Password: ")
        pass := gopass.GetPasswd()
        // Do something with pass
    }
    

    3- 代替for _, c := range bytes.Runes(password) { 你可以使用:for _, r := range password {,如下代码:

    d := make([]rune, 0, utf8.RuneCount([]byte(password)))
    for _, r := range password {
        if !unicode.IsControl(r) {
            d = append(d, r)
        }
    }
    fmt.Println(string(d))
    

    4- 您也可以将strings.Replace 用于 VT100 代码:

    password = strings.Replace(password, "\x1b[A", "", -1)
    

    请看:http://www.ccs.neu.edu/research/gpc/MSim/vona/terminal/VT100_Escape_Codes.html

    【讨论】:

      猜你喜欢
      • 2015-05-14
      • 2016-03-11
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      相关资源
      最近更新 更多