[QT]构建正则表达式测试

正则表达式是个强大的东西

暂时先记录一个用法:

QString str = "Peak memory: KEY s";
QString data = "Peak memory: 24.1 s";

需要构建一个可以匹配 data 的正则表达式,模板为 str ,其中KEY代表需要提取的数据。

PS: 需要注意的是 生成表达式中各种空格时候 \ 的用法,什么时候用一个,什么时候用2个或者4个,搞错了的话就不会进入if条件语句了。

#include <QApplication>
#include <QtGui>
#include <QLabel>
#include <QString>

#include <iostream>
using namespace std;

void generateReg(const QString &data, const QString &str)
{
	Q_ASSERT(str != NULL && "Wrong input");

	QString dst = str.trimmed();
	
	// generate reg expression
	dst.replace(QRegExp("\s+"), "(?:\s+)");
	dst.replace("KEY", "([1-9]+\.{,1}[0-9]*)");

	//dst = "Peak memory:(?:\s+)([1-9]+\.{,1}[0-9]*)(?:\s+)s";
	cout << "The reg pattern should be: " << "Peak memory:(?:\s+)([1-9]+\.{,1}[0-9]*)(?:\s+)s" << endl;
	cout << "The dst String:            " << dst.toStdString() << endl;

	QRegExp rx(dst);
	int pos = data.indexOf(rx);
	
	if (pos > -1)
	{
		cout << endl << "RegExp worked:)" << endl;
		QStringList capedStr = rx.capturedTexts();
		qDebug() << capedStr;
	}
}

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);

	QString str  = "Peak memory:   KEY s";
	QString data = "Peak memory:   241 s";
	generateReg(data, str);

	return a.exec();
}

  结果如下:

[突然想起有的地方代码可能看不到,还是贴着文本格式备用]

// 突然想起有可能看不了图片
#include <QApplication>
#include <QtGui>
#include <QLabel>
#include <QString>

#include <iostream>
using namespace std;

void generateReg(const QString &data, const QString &str)
{
Q_ASSERT(str != NULL && "Wrong input");

QString dst = str.trimmed();

// generate reg expression
dst.replace(QRegExp("\s+"), "(?:\s+)");
dst.replace("KEY", "([1-9]+\.{,1}[0-9]*)");

//dst = "Peak memory:(?:\s+)([1-9]+\.{,1}[0-9]*)(?:\s+)s";
cout << "The reg pattern should be: " << "Peak memory:(?:\s+)([1-9]+\.{,1}[0-9]*)(?:\s+)s" << endl;
cout << "The dst String: " << dst.toStdString() << endl;

QRegExp rx(dst);
int pos = data.indexOf(rx);

if (pos > -1)
{
cout << endl << "RegExp worked:)" << endl;
QStringList capedStr = rx.capturedTexts();
qDebug() << capedStr;
}
}

int main(int argc, char *argv[])
{
QApplication a(argc, argv);

QString str = "Peak memory: KEY s";
QString data = "Peak memory: 241 s";
generateReg(data, str);

return a.exec();
}

原文地址:https://www.cnblogs.com/dawnWind/p/QT_01.html