dsieyx2015 2016-08-26 23:09
浏览 9

如何将控制序列与输入字符串分开

I have a sample program to accept passwords on my terminal, and I'm using the terminal package for this. However, when I press any of the arrow keys by mistake while inputting my password I get some weird errors.

I wanted to separate my input password and then only use that for authorization. The following is what I tried.

My input string is

// 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("
INVALID PWD ")
                } else {
                    d = append(d, c)
                }
            }
fmt.Println("

", fmt.Sprintf("%c", d))

Here it prints [Aabcd in the end.

Is there anyway I can only capture/print the input characters without the [A here ?

Thanks

  • 写回答

1条回答 默认 最新

  • dqtok88424 2016-08-27 04:51
    关注

    1- If you need to separate the control sequence from input string, You may use unicode.IsControl(r):

    IsControl reports whether the rune is a control character. The C (Other) Unicode category includes more code points such as surrogates; use Is(C, r) to test for them.

    2- Also See: 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- instead of for _, c := range bytes.Runes(password) { you may use: for _, r := range password {, as the following code:

    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- Also you may use strings.Replace for VT100 codes:

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

    And see: http://www.ccs.neu.edu/research/gpc/MSim/vona/terminal/VT100_Escape_Codes.html

    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程