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

来源:互联网 发布:淘宝充值店没有人买 编辑:程序博客网 时间:2024/04/30 04:19

关键词: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 -----------------------------