Qt 正则表达式检测密码格式

关键词:Qt 正则表达式 QRegExp QMessageBox

1、建立Qt Application工程,设计UI[一个输入框,一个按钮];

2、Widget.h文件:

          #ifndefWIDGET_H

 #define WIDGET_H
 
 #include <QWidget> 
 #include <QRegExp> 
 #include <QMessageBox> 
 
 namespace Ui { 
       class Widget; 
 } 
 
 class Widget : public QWidget 
 { 
      Q_OBJECT 
 
     public: 
      explicit Widget(QWidget *parent = 0); 
     ~Widget(); 
 
   private: 
       Ui::Widget *ui; 
        QRegExp rx; 
        QMessageBox msgBox; 
   private: 
        void init(); //初始化函数 
 
   private slots: 
        void checkPwd(); 
 }; 
 
 #endif // WIDGET_H 
 

3、Widget.cpp

    #include "widget.h"

    #include "ui_widget.h"

 
    Widget::Widget(QWidget *parent) : 
     QWidget(parent), 
    ui(new Ui::Widget) 
   { 
         ui->setupUi(this); 
          this->init(); 
   } 
 
   Widget::~Widget() 
   { 
         delete ui; 
   } 
 
    void Widget::init() 
   { 
         //建立信号和响应函数 
        connect(ui->pushButton,SIGNAL(clicked()),SLOT(checkPwd())); 
 
        rx.setPatternSyntax(QRegExp::RegExp); 
        //对大小写字母敏感,即区分大小写 
        rx.setCaseSensitivity(Qt::CaseSensitive); 
       //匹配格式为所有大小写字母和数字组成的字符串,位数不限 
        rx.setPattern(QString("^[A-Za-z0-9]+$")); 
  } 
 
   void Widget::checkPwd() 
   { 
        QString pwd = ui->lineEdit->text(); 
        if(pwd.isEmpty())  //检测密码输入框是不是为空 
        { 
          ui->label2->setText("Password cant be empty!");  
          ui->label2->setStyleSheet("color: rgb(255, 78, 25);");; 
        } 
       else 
      { 
          ui->label2->setText(""); 
          if(rx.exactMatch(pwd)) 
           
            msgBox.setText("The password format is Right"); 
            msgBox.exec(); 
          } 
          else 
           { 
               msgBox.setText("Sorry,The password format is wrong!!\n 
                                    \nPlease reenter your password."); 
                 msgBox.exec(); 
           } 
      } 
 
   } 
 4、main.cpp不用修改。 
5、运行结果如下: 
    Qt <wbr>正则表达式检测密码格式 
   当输入特殊字符时会提示错误:
 
    Qt <wbr>正则表达式检测密码格式
 
 
//------------------------------ THE END ----------------------------- 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值