很长时间没写过博客了,重新捡起来,正好最近在使用Boost做项目,就先写一些Boost相关的知识吧。
写了一个简单的QtGUI Demo来测试boost正则表达式,主程序如下:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_match_clicked()
{
QLineEdit * srcEdit = this->findChild<QLineEdit *>("srcEdit");
QLineEdit * matchEdit = this->findChild<QLineEdit *>("matchEdit");
std::string src_data = srcEdit->text().toUtf8().data(); //源文本
std::string match_data = matchEdit->text().toUtf8().data(); //匹配模式
boost::regex regex(match_data);
if(boost::regex_match(src_data, regex))
{
qDebug()<<"Match"<<endl;
}
else
{
qDebug()<<"Un-Match"<<endl;
}
}
使用上面代码,输入如下参数:
srcEdit = "test",
matchEdit = "te"
输出 Un-Match
输入:
srcEdit = "test"
matchEdit = "te.*"
输出Match
所以上述正则匹配的方式必须是正则表达式完全匹配文本才行。
下面再加上查找子串的代码,代码如下:
void MainWindow::on_SubPartten_clicked(){QLineEdit * srcEdit = this->findChild<QLineEdit *>("srcEdit");QLineEdit * matchEdit = this->findChild<QLineEdit *>("matchEdit");std::string src_data = srcEdit->text().toUtf8().data();std::string match_data = matchEdit->text().toUtf8().data();boost::regex regex(match_data);boost::match_results<std::string::const_iterator> what;if(0 == boost::regex_match(src_data, what, regex, boost::match_default)){
qDebug()<<"Un-Match"<<endl;}
else{
qDebug()<<"Match"<<endl;for (unsigned int i = 1; i < what.size(); i++){
qDebug()<<i<<" "<<what[i].str().c_str()<<endl;}
}
}输入:
srcEdit= "2013/05/13";
matchEdit = "(\d+)/(\d+)/(\d+)"; //注意,我是在QEdit中编辑的,如果是在代码中写,需要改为(\\d+)/(\\d+)/(\\d+)
输出如下:
Match
1 2013
2 05
3 13