对正则表达式以前没了解过,这次用到大概看了一下,感觉挺复杂的,没怎么太懂,所以对 QRegExp 也没完全理解,就直接贴代码了:
main.cpp
以下是测试结果:
regexp.h
- #ifndef REGEXP_H
- #define REGEXP_H
- #include <QtGui/QDialog>
- #include <QtGui/QLineEdit>
- #include <QtGui/QTextEdit>
- #include <QtGui/QLabel>
- #include <QtGui/QPushButton>
- #include <QtGui/QListWidget>
- #include <QtGui/QVBoxLayout>
- class RegexpConner : public QDialog
- {
- Q_OBJECT
- public:
- RegexpConner( QWidget *parent = 0, Qt::WFlags flags = 0 );
- ~RegexpConner();
- private slots:
- void onGet ();
- private:
- QLabel *m_labelRegexp;
- QLabel *m_labelText;
- QLabel *m_labelResult;
- QLabel *m_labelIndex;
- QLineEdit *m_leditRegexp;
- QLineEdit *m_leditIndex;
- QTextEdit *m_teditText;
- QListWidget *m_listResult;
- QPushButton *m_btnGet;
- QHBoxLayout *m_hboxLayout;
- QVBoxLayout *m_vboxLayout;
- };
- #endif // REGEXP_H
- #include "regexp.h"
- RegexpConner::RegexpConner( QWidget *parent, Qt::WFlags flags )
- : QDialog( parent, flags )
- {
- m_labelRegexp = new QLabel( "regexp:" );
- m_labelText = new QLabel( "text:" );
- m_labelResult = new QLabel( "result:" );
- m_labelIndex = new QLabel( "index:" );
- m_leditRegexp = new QLineEdit;
- m_leditIndex = new QLineEdit;
- m_teditText = new QTextEdit;
- m_listResult = new QListWidget;
- m_btnGet = new QPushButton( "GET" );
- m_hboxLayout = new QHBoxLayout;
- m_hboxLayout->addWidget( m_btnGet );
- m_hboxLayout->addWidget( m_labelIndex );
- m_hboxLayout->addWidget( m_leditIndex );
- m_vboxLayout = new QVBoxLayout( this );
- m_vboxLayout->addWidget( m_labelText );
- m_vboxLayout->addWidget( m_teditText );
- m_vboxLayout->addWidget( m_labelRegexp );
- m_vboxLayout->addWidget( m_leditRegexp );
- m_vboxLayout->addLayout( m_hboxLayout );
- m_vboxLayout->addWidget( m_labelResult );
- m_vboxLayout->addWidget( m_listResult );
- setFixedSize( 500, 500 );
- connect( m_btnGet, SIGNAL(clicked()), this, SLOT(onGet()) );
- }
- RegexpConner::~RegexpConner()
- {
- }
- void RegexpConner::onGet()
- {
- m_listResult->clear();
- QString text = m_teditText->toPlainText();
- QString exp = m_leditRegexp->text();
- if( text.isEmpty() || exp.isEmpty() )
- return;
- int index = m_leditIndex->text().toUInt();
- QRegExp qregexp( exp );
- int length = 0;
- int idx = qregexp.indexIn( text, 0 );
- while( -1 != idx ) {
- int num = qregexp.numCaptures();
- QString str = qregexp.cap( index );
- if( !str.isEmpty() ) {
- QListWidgetItem *item = new QListWidgetItem( str );
- m_listResult->addItem( item );
- }
- length = qregexp.matchedLength();
- idx = qregexp.indexIn( text, idx + length );
- }
- }
main.cpp
- #include "regexp.h"
- #include <QtGui/QApplication>
- #include <QRegExp>
- #include <QTextCodec>
- #include <QObject>
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- RegexpConner rc;
- rc.show();
- return a.exec();
- }
以下是测试结果:
转载:http://blog.youkuaiyun.com/kusey/article/details/7383184